When it comes to iterating over items in an array, JavaScript offers a lot of ways out of the box:
- while loops
- for loops
- for of
- map
- forEach
- for in
But which one should you use?
Performance
The pragmatic answer
With the above in mind, here is some rule of thumb.
- Use
for of
often for readability. - Use
for i++
when performance is critical or you need the index for other operations. - Avoid
forEach
andfor in
as they are 99% slower than regularfor
loops. - Do NOT use
map
unless you want to store the returned array in a variable.