for...of

Non-standard

Summary

Iterates over iterable objects (including arrays, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

Statement
Implemented in: None
ECMA Version: ECMAScript 6th Edition proposal

Syntax

for (variable of object)
  statement

Parameters

variable
On each iteration a value of a different property is assigned to variable.
object
Object whose enumerable properties are iterated.

Examples

The following example shows the difference between a for...of loop and a for...in loop. While for...in iterates over property names, for...of iterates over property values:

let arr = [ 3, 5, 7 ];
arr.foo = "hello";

for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // logs "3", "5", "7"
}

Iterating over DOM collections like NodeList : the following example adds a read class to paragraphs that are direct descendants of an article:

let articleParagraphs = document.querySelectorAll("article > p");

for (let paragraph of articleParagraphs) {
  paragraph.classList.add("read");
}

You can also iterate over generators:

// NOTE: "function*" is not supported yet in Firefox.
// Remove the asterisk in order for this code to work in Firefox 13

function* fibonacci() { // a generator function
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

for (let n of fibonacci()) {
    // truncate the sequence at 1000
    if (n > 1000)
        break;
    print(n);
}

Browser compatibility

  • Desktop
  • Mobile

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 13.0 (13) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 13.0 (13) ? ? ?

See also

Tags (4)

Edit tags

Attachments (0)

 

Attach file