MDN’s Definition for forEach and map Methods
forEach()
method executes a provided function once for each array element.map()
method creates a new array populated with the results of calling a provided function on every element in the calling Array.
const grp = [0,1,2,3,4,5];
forEach() mutates the original data and has no return value.
const newGrp= grp.forEach(num => num * 4); console.log(newGrp); // undefined
On the other hand, map() does not mutate the original data. It returns a new array.
const newGrp = grp.map(num => num * 4); console.log(newGrp) // [ 0,4,8,12,16,20 ]
Note
- forEach is more performant when compared to map is less performant.
- return value for forEach is undefined while map returns new Array.
forEach()
may be preferable when you’re not trying to change the data in your array.