Menu

30 October 2014

Exact Difference between forEach and map function in JavaScript


If you want to iterate over Array in JavaScript then you have two options in your hand
Array.prototype.forEach
and
Array.prototype.map

I wanted to know the exact answer and there were huge list of answers.
Many were totally incorrect.
So I opted second way to find difference. I went to MDN and downloaded polyfill for forEach and map function.

It turns out there is only one difference in forEach and map function.

map function in JavaScript Array do exactly same as forEach but in addition, map function also return Array.

So, forEach is subset for map function.

I never use forEach function in my code. I always use map function.
Even of you do not want to use Array returned by map function, you need not to worry as It will be collected back !



--
Narendra Sisodiya
UI Architect @
Unicommerce
Delhi - Bharat