What is for…of loop in JavaScript?

What is for..of loop

In JavaScript for…of is a loop over iterable objects. This iterable object includes array, string, typedArray, set map, array like objects such as arguments, NodeList etc.

Syntax of for..of loop:

for (variable of iterable) {
  // statement; variable holds the value from iterable
}

for..of loop with an array:

let iterable = [60, 200, 500];
for (let value of iterable) {
    console.log(value);
}
// Output
// 60
// 200 
// 500

for..of loop with a string:

let iterable = 'JS';
for (let value of iterable) {
    console.log(value);
}
// Output
// J
// S 

for..of loop with a Map:

let iterable = new Map([['Joe', 24], ['Jenny', 20]]);
for (let item of iterable) {
    console.log(item);
}
// Output
// ['Joe', 24]
// ['Jenny', 20] 

for..of loop with a Set:

let iterable = new Set([33, 74, 33, 99]);
for (let item of iterable) {
    console.log(item);
}
// Output
// 33
// 74 
// 99

for..of loop with arguments object:

var getTotal = function(){
    for (let item of arguments) {
        console.log(item);
    }
};
getTotal(20, 30 , 50);
// Output
// 20
// 30 
// 50 

for..of loop with DOM NodeList:

const btnElements = document.querySelectorAll('span.btn');
for (const button of btnElements) {
    button.addEventListener('click', function(){
        // Statements
    });
}

for..of loop can not be used with Object:

If we try to use for..of loop with an object then it throws an uncought typeError. As the JavaScript objects are not iterable, it can not loop over an object. See the code segment below:

let iterable = {name: 'Joe Smith', age: 24};
for (let value of iterable) {
    console.log(value);
}
// Uncaught TypeError: iterable is not iterable