Cover by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Iteration

Mozilla’s JavaScript extensions introduce new iteration techniques, including the for each loop and Python-style iterators and generators. They are detailed in the subsections below.

The for/each Loop

The for/each loop is a new looping statement standardized by E4X. E4X (ECMAScript for XML) is a language extension that allows XML tags to appear literally in JavaScript programs and adds syntax and API for operating on XML data. E4X has not been widely implemented in web browsers, but it is supported by Mozilla’s JavaScript 1.6 (released in Firefox 1.5). In this section, we’ll cover only the for/each loop and its use with non-XML objects. See E4X: ECMAScript for XML for details on the rest of E4X.

The for each loop is much like the for/in loop. Instead of iterating through the properties of an object, however, it iterates through the values of those properties:

let o = {one: 1, two: 2, three: 3}
for(let p in o) console.log(p);       // for/in: prints 'one', 'two', 'three'
for each (let v in o) console.log(v); // for/each: prints 1, 2, 3

When used with an array, the for/each loop iterates through the elements (rather than the indexes) of the loop. It typically enumerates them in numerical order, but this is not actually standardized or required:

a = ['one', 'two', 'three'];
for(let p in a) console.log(p);       // Prints array indexes 0, 1, 2
for each (let v in a) console.log(v); // Prints array elts 'one', 'two', 'three'

Note that the for/each loop does not limit itself to the array elements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required