Javascript - for...of

Introduction

for...of loop allows iterating over iterable objects such as array, map, set, string, etc.

Consider a simple for-loop for iterating over an array:

let names = ['A', 'B', 'C']; 

for (let i = 0; i<names.length; i++) { 
        console.log(names[i]); 
} 

We can achieve the same iteration logic with lesser and cleaner syntax using the for-of syntax:

let names = ['A', 'B', 'C']; 

for (let name of names) { 
    console.log(name); 
} 

The value you loop over using for...of must be an iterable.

An iterable is an object that is able to produce an iterator, which is used by the for...of loop.

The for...of loop can work for arrays, DOM NodeList object, the arguments object, and String objects.

The following code shows how to use for-of loop to iterate over a string value:

for (let char of 'abc') { 
    console.log(char); 
} 

for...in loop is used to iterate over the enumerable properties (or keys) of an object.