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


for (variable of iterable) {

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

Object whose enumerable properties are iterated.

How to use

For Array

let arr = [1, 2, 3];

for (let val of arr) {;

// 1
// 2
// 3

For String

let str = "hi";

for (let val of str) {;

// "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

You May Also Like

About the Author: admin