Home

JavaScript Iterations: When to use map, foreach, for in, for of, for and while loops

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

How each of these methods compare with one another
Click here to run the tests yourself

The pragmatic answer

With the above in mind, here is some rule of thumb.

  1. Use for of often for readability.
  2. Use for i++ when performance is critical or you need the index for other operations.
  3. Avoid forEach and for in as they are 99% slower than regular for loops.
  4. Do NOT use map unless you want to store the returned array in a variable.