How to loop through array-like objects
Array-like object in Javascript is an object which has a length property of non-negative integer. It usually has some indexed properties. In most cases you won't be able to use any of the array methods such as forEach, map, join, etc.
If you're working in a browser environment with JavaScript, the most common array-like object you probably encounter is a NodeList - you can get it by running document.querySelectorAll('p')
in your browser's console. You may choose to get different element, not necessarily a paragraph.
When you log the output, you can see that what you've got (assuming the elements on the page exists) is NodeList. You may use JavaScript's forEach method to iterate over the NodeList but this wasn't always the case. Keep in mind though that other array methods might still not work on NodeList (at the time of writing this post).
Let's have a quick look on the structure of array-like object (not a NodeList):
const animalsInArrayLikeObject = {
"0": "Dog",
"1": "Cat",
"2": "Bird",
"length": 3
};
In order to iterate over the animalsInArrayLikeObject
, we can't call forEach directly unless it would be a NodeList. We have couple of options:
// Create new shallow copy of the Array instance from an array-like object
Array.from(animalsInArrayLikeObject).forEach(...);
// We can call slice method
Array.prototype.slice.call(animalsInArrayLikeObject).forEach(...);
// We can call forEach indirectly by using a call method
Array.prototype.forEach.call(animalsInArrayLikeObject, callback);
Converting array-like object to array is the easiest way to go about it if you want to have access to all array methods and iterate over the items without hassle. Let me know in the comments if you know another trick to iterate over the array-like objects. Happy coding!