The new ES6 for…of loop

The JavaScript's For...of loop structure is syntactic caster sugar dusted over the good old for statement. It's an extremely capable loop that can iterate almost anything you give it.

Basically, for...of iterates over the values of an array, not keys.

A bit of looping history

During the neolithic era we had to loop like this:

var testArray = [2, 3, 5, 7, 11];
for (var i = 0; i < testArray.length; i++) {
    // Outputs: 235711

Then ES5 gave us the forEach, and an access to the array value without any intermediate steps:

testArray.forEach(function(value) {
    // Outputs: 235711

That feels pretty good (read more about forEach here). But, you can’t break, and you can’t straight up iterate a nodelist with forEach.

Then, finally, ES6 brought us the for...of loop, which liberates us from, pretty much, all the looping limitations.

The for...of loop

Iterate an array

var testArray = [2, 3, 5, 7, 11];
for (var value of testArray) {

    if (value > 5) {
        break; // Can break

Iterate a string

For...of can also iterate a string:

var name = 'Slartibartfast';
for (var letter of name) {
    console.log(letter + '.');
    // S.l.a.r.t.i.b.a.r.t.f.a.s.t

Loop over a NodeList

Finally this is doable without for loop and without any forEach shenanigans:

var listItems = document.querySelectorAll('ul > li');

for (var item of listItems) {


for...of seems to be slower than for, but that’s okay. Here’s the test I used.

Screenshot 2016-03-08 08.48.31


for...each can loop over almost anything you throw at it: Maps, Sets, Generators, you name it. Read more about in MDN.

Club-Mate, the beverage →