Most Asked JavaScript Interview Question - Difference between map() and forEach()

Deepa Jarout
2 min readJul 4, 2022

--

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.

map() example by deepajarout

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.

forEach() example by deepajarout

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.

Difference between map() and forEach() by deepajarout

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.

Difference between map() and forEach() by deepajarout

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.

--

--

Deepa Jarout

I am Software developer.I like problem solving, traveling, photography, dancing, video games, conversation.I like to explore new places with different tradition