Few JavaScript loops you probably hadn’t thought of

Here are a few uncommon ways to loop in JavaScript. These might or might not come handy at some point of your developer life.

Length-less for loop

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".

Reverse for loop

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.

Reverse while loop

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).

Looping string with for...of

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)
}

Resources

Some of the techniques are lifted from this SO thread.