JavaScript - ES6 for-of loop

[Updated: Nov 23, 2018, Created: Nov 13, 2018]

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


Looping arrays

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

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()) {

Using ES6 Array.prototype.values:

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

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) {

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) {

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) {

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) {

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) {
//destructuring pattern
for (let [k, v] of m) {
    console.log(`key = ${k}, value = ${v}`);

See Also