JavaScript for…of Loop

A lot of powerful loops in javascript but for-of is a new loop in ES6 that replaces both for-in and forEach() and supports the new iteration protocol.

Use it to loop over iterable objects (Arrays, strings, Maps, Sets, etc.; see Chap. “Iterables and iterators”)

Syntax


for (variable of iterable) {
    statement
}

variable

On each iteration, a value of a different property is assigned to a variable.

Iterable

An object whose enumerable properties are iterated.

How to use

For Array


let arr = [1, 2, 3];

for (let val of arr) {
    console.info(val);
}

// 1
// 2
// 3

For String


let str = "hi";

for (let val of str) {
    console.info(val);
}

// "h"
// "i"

Access both elements and their indices while looping over an Array (the square brackets before of mean that we are using destructuring):


var arr = [10, 20];
for (const [i, el] of arr.entries()) {
    console.log(`${i}. ${el}`);
}

// Output:
// 0. 10
// 1. 20

About the Author: Pankaj Bisht