Looping in JavaScript ES5 and ES6: forEach and for...of
JavaScript has a few ways to loop over arrays and other types of data. It is a pretty common task for front‑end developers working with data, and in this post, we'll go over some of the methods that JavaScript offers ‑ especially now with the new ES6 standard.
The 'Old' Way
The original way to iterate over an array with JavaScript has a pretty messy‑looking syntax:
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];for (var i = 0; i < a.length; i++) { console.log(a[i]);}With this code, we're setting up our iteration to start on 0, and loop as long as i is less than the length of our array (a). We use the iteration count (held in the variable i) as a key to select entries in the array as we loop over them.
ES5
With ES5, we got a new method of looping over data. We can use ES5's forEach to iterate over the full array, like this:
a.forEach(function (item) { console.log(item);});As you can see, this is clearly much nicer; it's clearer to read and easier to write and provides a nice piece of syntactic sugar to help developers.
However, it's not all sunshine and rainbows. There are things that can't be done with forEach, such as iterating over a NodeList (a collection of HTML elements). This is something that comes up frequently in front‑end development, so this seems like an obvious omission; employing workarounds to get forEach to work with NodeLists is a bit of a pain.
We also can't break a forEach iteration, which means if we're searching for a particular item and we find it, the iteration continues to run unnecessarily.
ES6
Enter ES6, and the for...of method. Using the same example again:
for (item of a) { console.log(item); if (item == 7) { break; }}For me, this looks even nicer than the ES5 forEach method. It's clear, concise, and allows you to set up a variable to be used inside the for loop clearly without having to pass it through as a parameter via function(). It also allows us to break the loop whenever we need.
Using this, you can even iterate over NodeLists and through strings.
Ultimately, looping over arrays, NodeLists and other types of data is a task every developer has to do at some point or another. As time has moved forwards, and we got to ES5 and then through to ES6, the ways that JavaScript allows us to carry that task out have evolved and changed.