To understand the differences between the two, let's look at what each function does.
forEach
const a = [1, 2, 3];
const doubled = a.forEach((num, index) => {
// Do something with num and/or index.
});
// doubled = undefined
map
const a = [1, 2, 3];
const doubled = a.map((num) => {
return num * 2;
});
// doubled = [2, 4, 6]
The main difference between .forEach and .map() is that .map() returns a new array. If you need the result, but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an array, forEach is a fine choice.
Adapted from the Front End Interview Handbook by Yangshun Tay and contributors (MIT License). Source
Spotted a mistake or a rights concern? Report an issue