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 ofoften for readability. - Use
for i++when performance is critical or you need the index for other operations. - Avoid
forEachandfor inas they are 99% slower than regularforloops. - Do NOT use
mapunless you want to store the returned array in a variable.