Difference between map and forEach?

map builds and returns a new array from the callback's return values, so it is for transforming data; forEach returns undefined and exists only for side effects.

mapforEach
ReturnsNew array, same lengthundefined
PurposeTransform dataPerform side effects
ChainableYes (.map().filter())No
Uses callback's return valueYesNo (ignored)
Mutates originalNo (unless your callback does)No (unless your callback does)
Early exitNoNo

How to choose

Ask: "Do I need the result?"

  • Yes: use map (or filter/reduce).
  • No, I am logging, saving, rendering imperatively or updating something else: use forEach or for...of.

Common mistakes

  • Using map for side effects and ignoring the result. It works, but creates a throwaway array and hides intent.
  • Using forEach and pushing into an outer array to build a result. That is exactly what map is for.
  • Forgetting to return inside map with a block body, which gives [undefined, undefined, ...].

Performance

Both are similarly fast. The difference is clarity and the extra array map allocates. Pick based on intent, not speed.

Code example

js
1const prices = [10, 20, 30];
2
3// map: produce a new array
4const doubled = prices.map((p) => p * 2);
5console.log(doubled); // [20, 40, 60]
6
7// forEach: side effects only, returns undefined
8const result = prices.forEach((p) => console.log("price", p));
9console.log(result); // undefined
10
11// Anti-pattern: building an array with forEach
12const viaForEach = [];
13prices.forEach((p) => viaForEach.push(p * 2));
14console.log(viaForEach); // works, but map says it better
15
16// Common map bug: block body without return
17const broken = prices.map((p) => {
18 p * 2;
19});
20console.log(broken); // [undefined, undefined, undefined]
21
22// map chains, forEach cannot
23const summary = prices
24 .map((p) => p * 1.2)
25 .filter((p) => p > 15)
26 .map((p) => p.toFixed(2));
27console.log(summary); // ["24.00", "36.00"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app