Close

JavaScript - ES6 for-of loop

[Last Updated: Nov 23, 2018]

ES6 introduce for-of loops as an alternative to for-in and forEach() loops.

Examples

Looping arrays

let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
    console.log(fruit);
}

Using ES6 Array.prototype.entries and destructuring syntax:

let fruits = ["apple", "banana", "orange"];
for (let [index, value] of fruits.entries()) {
    console.log(index + " - " + value);
}

Using ES6 Array.prototype.keys:

let fruits = ["apple", "banana", "orange"];
for (let index of fruits.keys()) {
    console.log(index);
}

Using ES6 Array.prototype.values:

let fruits = ["apple", "banana", "orange"];
for (let value of fruits.values()) {
    console.log(value);
}

We can also use break and continue inside for-of loops.

for-of loop can be used for all objects which are iterable.

Various JavaScript built-in object are iterable, e.g. String, Array, Map, Set etc. We can also create our own iterables (next tutorial).

Lopping string

Lopping though string's characters:

let str = "examples";
for (let c of str) {
    console.log(c);
}

Not all objects can be looped

We cannot iterate objects unless they implement iterable protocol (next tutorial).

let obj = { x: 2, y: 'test' };
for (let v of obj) {
    console.log(v);
}

But we can use for-in loop for any objects:

let obj = { x: 2, y: 'test' };
for (let k in obj) {
    console.log(`${k} = ${obj[k]}`);
}

Looping function arguments

function test() {
    for (let arg of arguments) {
        console.log(arg);
    }
}

test(1, 2, 'three');

Looping Set

Using ES6 Set:

let s = new Set([2, 3, 1, 2, 1]); //retains only unique items
for (let e of s) {
    console.log(e);
}

Looping Map

Using ES6 Map:

let m = new Map([
    ['one', 1],
    ['two', 2]
]); //constructor using an array of entries (destructuring syntax)
for (let e of m) {
    console.log(e);
}
//destructuring pattern
for (let [k, v] of m) {
    console.log(`key = ${k}, value = ${v}`);
}

See Also