DEV Community

Joe Eames for Thinkster

Posted on

Working with Array-Like Objects

JavaScript has this very strange construct called an array-like.

Array-like objects aren’t arrays, they’re objects that have a length property and indexed properties (indexed properties have a numeric identifier). They are EXTREMELY simple to create.

image

Here I’ve created a simple array-like object. It has 5 properties. Those properties have the following keys: name, age, length, 0, and 1. We rarely see properties with a numeric key like this, but it’s totally valid.

There are certain things we can do with array-like objects. For example, we can loop over them with either for loops, or the very convenient “for of” loop.

image

These 2 loops will produce the same result when run against the variable we created above: they’ll log out ‘a’ and ‘b’. You can see that in this stackblitz project. These loops will ignore the name and age property. It only cares about the numeric properties. And only the numeric properties that are 0 through the length — 1. If we add another property with the key of 4 and leave length equal to 2, the new property isn’t included in the loop.

We frequently work with several common array-like objects. Strings are array-like objects. So is the special “arguments” object in functions. And if we get a DOM node list with querySelectorAll or something similar, those are array-like objects as well.

Here’s a simple example with a string

image

Now you may be wondering why this all matters. So there are array-like objects and we can loop over them. Who cares?

Well, the reason to be aware of this is that we’re missing out on some great functionality. Arrays have a whole bevy of useful features such as the map and filter function, or join, or push/pop, find, reduce, and on and on. This includes the spread syntax as well.

But array-like objects don’t have these features. So if we have an array-like object and we want to use one of these awesome methods, we can’t.

Or can we?

Thankfully, there’s actually a quick solution here: the Array.from() method. Array.from will take an array-like object and turn it into a true Array.

image

At this point, we now have a real Array, and can do all the normal Array things we may want to do.

image

Ok, so you’ve read about this. But you’re going to forget this by tomorrow. Want to actually learn and master these concepts? You need to actually DO them. I’ve created a short exercise that should take about two minutes to practice leveraging what you’ve learned to do something useful. Head over to that link and follow the directions. See if you can master array-like objects and Array.from to make your life easier.

Happy Coding!

Enjoy this discussion? Sign up for our newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Top comments (0)