A good[ish] website

Web development blog, loads of UI and JavaScript topics

Few JavaScript loops you probably hadn’t thought of

Filed under: JavaScript— Tagged with: iteration

Here’s 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 the i ins 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, now you know.

Reverse while loop

Here’s a simple looking reversed while loop:

const el = document.getElementsByClassName('hotdog')
const i = el.length

while (i--) {
  el[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) {


Some of the techniques are lifted from this SO thread.

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!