I remember the struggle and the misunderstanding as I was trying to iterate over a
NodeList collection with no success. In this article you’ll see how to convert an array-like object like
NodeList to a real
Array using different methods.
Axel Rauschmayer on array-like objects.
So why would you want an array from an array-like? To be able to iterate over it of course, oh and
reduce() too. Also note that the
NodeList object is iterable now using
forEach(), even though it’s not an
slice method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The arguments inside a function is an example of an ‘array-like object’.
Array-like objects on MDN
Array.prototype.slice is the slice function for arrays, and the
apply() methods let you manually set the value of this in the function.
The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.
“If it’s on the left-hand side of an equal sign then it’s rest. If not, it’s spread.”
In this case, it’s the spread syntax which helps to expand the
arrLike object into its elements, thus copying it to
The spread syntax makes converting an array-like to
Array look easy to follow and it’s also the shortest too if you’re into optimizing the number of bytes. This might be the most clean and beautiful option to use but the browser support it’s important when it comes to a decision.
On performance, I made some tests and it looks like
Array.prototype.slice.call() is the fastest with both alternatives being way slower. So I guess in the end it’s all about the project you’re working on and the browser support you’re targeting at. Easy. :)