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

```js
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](https://stackoverflow.com/a/157323/976972) answer recommends reverse for
loop in some cases:

```js
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:

```js
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Examples)
you throw at it, like a strings:

```js
const iterable = 'foo'

for (let letter of iterable) {
  console.log(letter)
}
```

## Resources

Some of the techniques are lifted from
[this SO thread](https://stackoverflow.com/questions/157260/whats-the-best-way-to-loop-through-a-set-of-elements-in-javascript).
