Loop through anything with javascript

Last updated August 31, 2021 by Jacob Paris

There are now four ways to open a for loop in javascript

While they differ a bit on speed and the variables they declare implicitly, the actual body of the for loop doesn't change much between the different methods.

For of

The easiest way to loop through an array is with the for…of loop

1const fruits = ['apple', 'banana', 'cherry']
2
3for (const fruit of fruits) {
4 console.log(fruit)
5}
6
7// apple
8// banana
9// cherry
10

We're not limited to arrays though, since all iterators work the same in javascript. That means we can just as easily loop through a string

1for (const letter of 'javascript') {
2 console.log(letter)
3}
4
5// j
6// a
7// v
8// a
9// s
10// c
11// r
12// i
13// p
14// t
15

Many emojis are stored as multiple codepoints, and some emojis are created by joining multiple other emojis.

For…of will iterate over them one by return, returning every πŸ‘¨ in a πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦

1for (const person of 'πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦') {
2 console.log(person)
3}
4
5// πŸ‘¨
6// πŸ‘©
7// πŸ‘§
8// πŸ‘¦
9

We can use the return keyword to break out of a function early. In a loop, we can use the continue keyword to break out of the current iteration and start the next iteration immediately.

1const sequence = [0, 1, 2, 3, 4, 5]
2
3for (const number of sequence) {
4 if (isOdd(number)) continue
5
6 console.log(number)
7}
8
9// 0
10// 2
11// 4
12

Loops also have the break keyword, which will cancel not only the current iteration but also the rest of the loop

1const sequence = [0, 1, 2, 3, 4, 5]
2
3for (const number of sequence) {
4 if (number >= 3) break
5
6 console.log(number)
7}
8
9// 0
10// 1
11// 2
12

At the end of every iteration, the current scope is discarded and a new one is opened, so it's ok to use const or let at the start

1for (const item of items)
2// or
3for (let item of items)
4

For await of

If you try to use await inside a loop, the execution will pause until the promise resolves and then it'll proceed as usual. To allow the loops to proceed concurrently, you can either await the promises before starting the loop or using for await of to do the same thing

1for (const x of await Promise.all(arrayOfPromises))
2// or
3for await (const x of arrayOfPromises)
4

For in

In javascript, objects are not strictly iterable. If you want to loop through the keys of an object, you can either use for in or convert the keys to an array

1const hashMap = {
2 abcd: { … },
3 abce: { … },
4 abcf: { … },
5 abcg: { … },
6 abch: { … }
7}
8
1for (const key of Object.keys(hashMap)) {
2 const value = hashMap[key]
3}
4// or
5for (const key in hashMap) {
6 const value = hashMap[key]
7}
8

If the only thing we need the key for is to access the value, we can skip a step and loop through the values directly

1for (const value of Object.values(hashMap) { … }
2

If we need both key and value, my preferred method is to use Object.entries, which returns a [key, value] pair, and destructure them right in the head the loop

1for (const [key, value] of Object.entries(hashMap)) { … }
2

Since arrays are just objects with numeric keys, we can use that same syntax to get the index of our array elements inside our loop

1for (const [i, element] of Object.entries(array)) { … }
2

To run a loop a specific number of times, we can create an array with that many elements and then loop through it.

Iterators skip over empty array slots, so we need to fill it with at least undefined first, and then optionally map its index

1const array = Array(25).fill() // [ empty, empty, empty, …]
2// or
3const array = Array(25).fill().map((_, i) => i) // [ 0, 1, 2, … ]
4
5for (const i of array) { … }
6

Classic for

The other option is to use the classic for loop syntax. This gives you the most control at the cost of readability.

1for (let i; i < 25; i++) { … }
2