A good[ish] website
Web development blog, loads of UI and JavaScript topics
Here’s few uncommon ways to loop in JavaScript. These might, or might not come handy at some point of your developer life.
You don’t necessarily need to get the length of the condition.
const el = document.getElementsByClassName('hotdog')
for (let i = 0; menu[i]; i++) {
el[i].className += ' some-extra-class'
}
Downside is that it won’t work on "arrays where null
, undefined
, false
, 0
, or ""
are valid elements".
This answer recommends reverse for loop in some cases:
const el = document.getElementsByClassName('hotdog')
for (let i = el.length - 1; i >= 0; i--) {
el[i].className += ' some-extra-class'
}
In reverse, loops are a bit speedier, that’s because i
is only evaluated once, and not on every iteration. Which is of course completely meaningless unless you’re dealing with iteration counts in their millions, but anyway.
Here’s a simple looking reversed while
loop:
const els = document.getElementsByClassName('hotdog')
const i = els.length
while (i--) {
els[i].className += ' some-extra-class'
}
When we subtract from the index with i--
, at some point the i
hits 0 and the loop stops (because 0 is a bottom value).
For...of can loop pretty much anything you throw at it, like a strings:
const iterable = 'foo'
for (let letter of iterable) {
console.log(letter)
}
Some of the techniques are lifted from this SO thread.
Comments would go here, but the commenting system isn’t ready yet, sorry.