DEV Community

Discussion on: The Most Useful JavaScript Array Methods Explained with Examples

Collapse
 
hnicolas profile image
Nicolas Hervé

There is another syntax that let you iterate over the elements of an array :

for (const element of array) {
  // do what you want
}
Enter fullscreen mode Exit fullscreen mode

I like the functional programming style but sometime it is good to be able to break the loop earlier.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan • Edited

That's true but for...of loop is very slow compared to normal for loop and forEach loop. So it should not be used when the performance matters.

Collapse
 
hnicolas profile image
Nicolas Hervé

It's true that for...of loop are slower, but not very slow compared to for loop. I think this cost is due to the fact that for...of loop work not only for arrays but for iterators.

Thread Thread
 
myogeshchavan97 profile image
Yogesh Chavan

Yeah, maybe. Here is a detailed analysis of the performance for all of them which is worth checking out

Thread Thread
 
alainvanhout profile image
Alain Van Hout • Edited

Interesting performance comparison. It's unfortunate that in the traditional for loop they did not include assigning arr[i] to a variable since that's inherently part of the other two cases.

Thread Thread
 
buphmin profile image
buphmin

I think these may be a bit off. I did a quick test using jsbench.me, with for...i as the baseline fastest: for...of 5% slower, forEach being 35% slower, and map being 45% slower. Note that run to run one may perform faster depending on what the compiler decides to optimize, which means you need to measure many runs and aggregate.

These results also make sense given the difference in how many memory allocations and references have to be made. For...i requires very little in the way of allocations, for of requires an allocation of the value variable, both forEach and map require the allocation of the function reference and the variable. If map or forEach are ever faster than for...i or for...of then it is a specific optimization on that version of the compiler and will likely fall behind once the compiler devs optimize for...i and for...of again.

Thread Thread
 
myogeshchavan97 profile image
Yogesh Chavan

I agree with you, It may depend on compiler optimization. Thanks for the detailed analysis👍