Using the spread operator to manage array-like objects

One of JavaScripts odd quirks is the existence of array-like objects. They look and feel like a typical array — especially for new JavaScript developers—but don’t always act as such.

For example, you’re unable to use handy iterators, like map, from the get-go — instead, you’ll have to use loops or other methods to access the data inside.

Last week, I wrote about object destructuring and touched a bit on how the spread operator can be used in conjunction with those tools to accomplish some common goals. The spread operator is also incredibly useful in its own right, and is quite helpful for dealing with these pseudo-arrays quite easily!


When I was first learning JavaScript, one of the biggest challenges I had with these array-like object was when I was using methods like querySelectorAll and getElementsByClassName to access elements directly on the DOM. These built-in methods return things like a nodelist or an HTMLCollection. Depending on what you’re working with, you may have access to some tools, but you can easily use the spread operator to create an array from these results. Using the spread operator will also preserve the original array-like object because it’s effectively creating a new array before mapping!

Let’s say, for example, you want to iterate over all of the elements with a given class name (click here to see the HTML for the example in a Codepen!):

let listFromClassName = document.getElementsByClassName("list-item");
listFromClassName.map(item => console.log(item));
//Result:
//Uncaught TypeError: listFromClassName.map is not a function

As it stands, this is not possible, because getElementsByClassName returns an HTMLCollection, which cannot be mapped! You can easily resolve this error by introducing the spread operator before the map:

[...listFromClassName].map(item => console.log(item));
//Result:
//<li class="list-item">Item One</li>
//<li class="list-item">Item One</li>
//(etc.)

The spread operator can also be applied to similar situations that arise with querySelectorAll and getElementsByTagName!


The spread operator can also be used to manage the arguments object available inside of functions. Like with the HTMLCollections, arguments is an array-like object:

function argsExample(x, y, z){
arguments.map(arg => console.log(arg))
}
argsExample("1", "2", "3");
//Result:
//Uncaught TypeError: arguments.map is not a function

Again, by simple trying to iterate over the arguments, you’ll receive an error stating that there is a type error. As with above, just used the spread operator to make arguments into an array on the spot:

function argsExample(x, y, z){
[...arguments].map(arg => console.log(arg))
}
argsExample("1", "2", "3");
//Result:
//"1"
//"2"
//"3"

Ultimately, spread operators are good way to deal with some of JavaScripts quirks related to array-like objects.

Links to the code used in this blog: