The fastest way to loop through an Array in Javascript

Mark O'Neill
February 26, 2021

The fastest way to loop in Javascript is the original for loop. Other methods such as forEach() provide easier ways to loops but take a little bit longer.

If you have a big array to loop through, and speed is a requirement, then for is your best friend.

copy code
const myArray = [1,2,3,4,5]

// caching the length of the loop is a contentious method 
// it may not add any additional speed boost
const arrLength =  myArray.length

for (i = 0; i < arrLength; i++) {
  console.log(`index ${[i]}: value is ${myArray[i]}`)

The results

This Gists blog post here has a nice comparison of the different operations and their benchmarked scores. Below are the results showing the average time it took each method to loop over an array with a length of 1 million:

  • for Loop - 24.84ms
  • for ... In - 36.44ms
  • forEach - 58.45ms
  • for in - 153.71ms

fastest != best

Shaving 12 milliseconds off your loop times won't make a noticeable difference to most applications. There are, however, a lot of other differences between the looping methods which you should also take into account, such as scoping and asynchronous behaviour.

In many cases, the best solution is the one that is easiest to write and easiest to read. Syntactic sugar makes everything sweeter.


Know a better answer? Join our our community and let us know.