In JavaScript, certain objects may resemble arrays, but they lack the array methods like map
, filter
, etc. These objects are often referred to as “array-like” objects. A common example of an array-like object is the NodeList returned by methods like querySelectorAll
.
The Array.from() JavaScript method provides a convenient way to convert these array-like objects to proper arrays. It takes an iterable object and returns a new Array instance. This allows you to access all the array methods and properties.
Let’s see the example of converting Array-like Objects to Arrays in JavaScript Using Array.from()
.
Example
Suppose you have a NodeList obtained by selecting all paragraph elements on a webpage:
const paragraphs = document.querySelectorAll('p'); // NodeList
Now, if you try to use array methods directly on paragraphs
, you’ll encounter an error because NodeList doesn’t have these methods.
paragraphs.map(paragraph => console.log(paragraph.textContent)); // Error: paragraphs.map is not a function
To work around this, you can convert paragraphs
to an array using Array.from()
:
const paragraphArray = Array.from(paragraphs); // Convert NodeList to Array
Now, paragraphArray
is a proper array, and you can use array methods on it:
paragraphArray.map(paragraph => console.log(paragraph.textContent)); // Logs the text content of each paragraph
Benefits:
- Simplicity:
Array.from()
provides a straightforward and concise way to convert array-like objects into arrays without the need for verbose iteration or manual conversion. - Compatibility: It works across modern browsers, making it a reliable solution for handling array-like objects consistently.
- Flexibility: You can use it with various iterable objects beyond just NodeList, such as argument objects or strings, making your code more versatile.
In summary, Array.from()
is a powerful method to convert array-like objects to arrays, enhancing the flexibility and functionality of your JavaScript code.
Being Tricky 😉
More Tricks
FAQs
NodeList objects, like those returned by querySelectorAll
, resemble arrays but lack built-in array methods. This is because NodeList is live and dynamic, unlike arrays. To use array methods, convert NodeList to an array using Array.from()
.
Array.from()
with other iterable objects?Yes, Array.from()
isn’t limited to NodeList. It works with arrays, strings, Sets, Maps, and array-like objects. For instance, you can convert strings into arrays of characters or Sets into arrays easily.