A good[ish] website
Web development blog, loads of UI and JavaScript topics
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.
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.
for...of
loopvar testArray = [2, 3, 5, 7, 11]
for (var value of testArray) {
console.log(value)
if (value > 5) {
break // Can break
}
}
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
}
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')
}
for...of
seems to be slower than for
, but that's okay. Here's the test I used.
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.