Most Asked JavaScript Interview Question - Difference between map() and forEach()
JavaScript Array function map() and forEach(). Let’s dive right into the topic and compare both array functions and know when to use which function and why.
Array.map()
The map
method receives a function as a parameter. Then it applies it to each element and returns an entirely new array (populated with the results of calling the provided function). The key takeaway is that it will always return the same number of items.
Array.forEach()
forEach()
method receives a function as an argument and executes it once for each element present in the array. However, instead of returning a new array (like in the case of map
), it returns undefined
.
As one can observe from the above outputs, the use-cases for these two functions are totally different from one another.
map
is used for changing each value of a given array, while forEach
is used to simplify iterating over an array without changing its values.
Differences
The first difference between map()
and forEach()
is the returning value. The forEach()
method returns undefined
whilemap()
returns a new array with the transformed elements.
The second difference between these array methods is the fact that map()
is chainable. You can perform reduce()
, sort()
, filter()
another method after performing a map()
method on an array, while it is not possible in the case of forEach()
because it returns undefined
.
Conclusion
If you want to change each value of the array — usemap
, but if you want to do other operations on each value of a given array — use forEach
. It doesn’t make sense to use map
if you don't want to change the array, and forEach
if you want to change each value.