Looping Objects is easy. Looping Arrays is also easy. Looping NodeLists is easy. They can be a little repetitive though and often take time to construct each loop and pass in the index, property, element or whatever…
Table of contents
There is no “standard” way of iterating over everything. We can use
Array.prototype.forEach to loop over Arrays (or the regular
for loop), a
for in loop for Objects, and a regular
for loop again for NodeLists or HTML collections. No, you’re not going to use that
Wouldn’t it be nice to just forget about what type of collection we’re looping, forget about browser support and write a nice little function that handles everything for us. Yes.
So I did…
forEach.js is a simple script, it’s not part of a library or even a module, it’s just a function, here’s its syntax and a quick example using an
forEach() for Arrays/NodeLists
You can loop over an Array or NodeList using a standard
for loop, however, NodeLists cannot be used in conjunction with the newer ECMAScript 5
Array.prototype.forEach. This script takes care of that in the same way it loops over an
Array, you’ll get the same stuff passed back:
forEach() for Objects
Object iteration is usually done via a
for in loop, we can wrap this up by passing back values which makes our loops cleaner and easier to manage:
Collection of items to iterate, could be an
Callback function for each iteration.
forEach is iterating over, to use as the
this value when executing callback.
For those interested, check out the code below, the latest version is available on GitHub.