DEV Community

loading...

JavaScript's friendliest for loop: for...of loop

runosaduwa profile image Runo-saduwa ・2 min read


For many years in JavaScript, we have been iterating over iterables using the for, for-in and forEach(in the case of arrays).

I can't imagine how hard programming will be without these structures, they have indeed saved lives but ES6 is here again, with yet another powerful, cleaner and in my opinion, the most friendliest for loop: the for...of loop.

The for...of loop allows iteration over iterable objects such as arrays, strings, maps, etc with lesser and cleaner syntax.

Let's consider a regular for-loop for iterating over an array:

  let names = ["runo", "peter", "saduwa"];

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

There's absolutely nothing wrong with this style, But with the for...of syntax we can achieve the same thing without having to initialize a counter variable i to keep track of the loop. See how we can use the for...of syntax to make our code much cleaner and readable:

  let names = ["runo", "peter", "saduwa"];

for(let name of names){
 console.log(name);
}
// runo
// peter
// saduwa

See how clean the code looks, the name variable represents each element in the names array.

Note: the value you loop over using the for...of loop must be an iterable. An iterable is simply an object that is able to produce an iterator. Examples of iterables in JavaScript are the arrays, strings, maps and sets, etc. Also node lists from the Dom tree.

Simple iteration over a string:

  let name = "Runo";

for(let letter of name){
console.log(letter)
}

// R
// u
// n
// o

Summary

The for...of loop is the latest for-loop in the JavaScript world that will help developers iterate over iterables such as arrays, strings, maps and sets with lesser and cleaner code. It also improves code readability with its focused syntax.

Happy Coding!!

Discussion

pic
Editor guide
Collapse
hsolatges profile image
hsolatges

You can use const keyword for the variable:

for(const name of names) console.log(name); 

And you can access indexes with Array.prototype.entries() through destructuring:

for(const [index, name] of names.entries()) console.log(`index: ${}, name: ${name}`)
Collapse
runosaduwa profile image
Runo-saduwa Author

Thanks for the input @hsolatges