DEV Community

Discussion on: Array.map() much slower than for loop

Collapse
 
atwright147 profile image
Andy Wright

It is slower because it has to create / initialise the callback function passed to it for every item.

There might be other reasons too

Collapse
 
s3pt1c4n profile image
Richard Pap

Exactly

Collapse
 
diek profile image
diek

As you say, and i want to add something, the map tool returns you an array with the result of every element through the callback, if you don't want this you shouldn't use it.

Collapse
 
henryjw profile image
Henry Williams

But isn't that essentially what the for loop is also doing?

Thread Thread
 
atwright147 profile image
Andy Wright

Correct. However, you should avoid using the for loop in general, because it will iterate over every property of the item passed to it including things which you might not want to iterate over (like a for in loop would do).

Alternatives to for include: forEach, for of, map etc