A blurred photograph of train rails in a tunnel

One of the common frustrations in looping through iterable elements in JavaScript is that they typically take a not-insignificant amount of time to setup: a classical for loop takes a variable, an iterator and a condition just to get started.

JavaScript’s new for…of loop has a native understanding of iterable structures, removing the need for much of that preparation and allowing you to get right to manipulating data.

A typical for…of loop starts with an array:

var jupiterMoons = ["Europa", "Ganymede", "Io", "Callisto", "Amalthea"];

for (var moon of jupiterMoons) {
  console.log(moon);
}

The result in the console is the contents of the array:

> Europa
> Ganymede
> Io
> Callisto
> Amalthea

moon is an entirely arbitrary name, in the context of the loop: it could be any valid word you wished.

A few notes:

  • you need to be a little careful what you apply for…of to. Some browsers haven’t yet made Nodelists iterable (NodeList.prototype[Symbol.iterator]); data gathered in document.querySelectorAll can be iterated over using for…of in the latest versions of Chrome and Firefox, for example, but not in the current version of Safari.
  • you can also use for…of to iterate over strings, maps, typedarrays, sets and generators.
  • for…of will preserve the order of elements in an array when reading or manipulating them (unlike for…in, which is not guaranteed to do so).
  • unlike forEach, you can use break, continue, and return in for…of
  • for…of works with collections as objects; other iterative work with objects should be done in for…in or object.keys.

Compatibility

for…of has great cross-browser support, so long as you keep to recent versions: Chrome 51, Edge (but not IE), and Opera 25. Firefox and Safari have older support: versions 13 and 7.1, respectively.

Photograph by Chris Smart, used under a Creative Commons license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.