What is the difference between map and forEach?
map returns a new array built from your callback's return values. forEach returns undefined and is only for side effects like logging. Use map to transform data and forEach to do something with each item.
Explain it simply
Imagine a teacher checking answer sheets. forEach is like the teacher walking through the class and ticking each sheet: something happens to each paper but she hands nothing back. map is like a teacher who returns a new pile of marks, one result per sheet.
Both call your function once per element with (item, index, array). The difference is the return value: map collects what your callback returns into a new array of the same length; forEach throws it away and returns undefined.
That is why chaining works on map (.map().filter()) but not on forEach.
Example
const fees = [100, 200, 300];
const withGst = fees.map((f) => f * 1.18);
console.log(withGst); // Output: [118,236,354]
const result = fees.forEach((f) => f * 2);
console.log(String(result)); // Output: undefined
fees.forEach((f) => console.log("paid " + f));
// Output: paid 100
// Output: paid 200
// Output: paid 300What to say in the interview
"map transforms each element and returns a new array of the same length, leaving the original untouched. forEach just runs a side effect and returns undefined. If I am not using the returned array, I use forEach or a for...of loop instead of map."
Common mistakes
- Using map only for side effects and ignoring the result.
- Trying to break out of forEach with break. It cannot be stopped early.