For Of

  • Used to iterate iterable objects

  • Loop values instead of keys

  • You can use break, continue in for of loop

  • won't loop over prototype like for in

Loop array

var arr = [1,2];

for(let val of arr){
    console.log(val);
}
// output
1
2

Iterare over arguments ( without converting it to array )

// else you might have done Array.from(arguments).forEach()
function getVal(){
    for(let val of argumants){
        console.log(val);
    }
}

Loop over dom nodes without converting it to array

var ps = document.querySelectorAll('p');

for(let paragraph of ps){
    paragraph.addEventListener('click', function(){});
}

Loop with index

var arr = ["Hemant",2, "Vinay"];

for(let [i, val] of arr.entries()){
    console.log(i, val);
}

// output
0 Hemant 
1 2 
2 Vinay

Obeject literal not iterable

var arr = {name: 'hemant', age: 20, loc: 'Hyderabad'};

for(let val of arr){
    console.log(val);
}
// TypeError: arr is not iterable

Iterate Set

var s = new Set();
s.add("one");
s.add(2);
s.add("three");

for(let val of s){
    console.log(val);
}
// output
one
2
three

Iterate Map

var m = new Map();
m.set("one", 1);
m.set('two', 2);

for(let val of m){
    console.log(val);
}

// output
["one", 1]
["two", 2]

Last updated

Was this helpful?