clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

The new ES6 for...of loop

Filed under: JavaScript— Tagged with: iteration

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++) {
  console.log(testArray[i])
  // Outputs: 235711
}

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

testArray.forEach(function (value) {
  console.log(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) {
  console.log(value)

  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) {
  item.classList.add('hello')
}

Speed

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

Conclusions

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

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!