JavaScriptEasy
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.
map | forEach | |
|---|---|---|
| Returns | New array, same length | undefined |
| Purpose | Transform data | Perform side effects |
| Chainable | Yes (.map().filter()) | No |
| Uses callback's return value | Yes | No (ignored) |
| Mutates original | No (unless your callback does) | No (unless your callback does) |
| Early exit | No | No |
How to choose
Ask: "Do I need the result?"
- Yes: use
map(orfilter/reduce). - No, I am logging, saving, rendering imperatively or updating something else: use
forEachorfor...of.
Common mistakes
- Using
mapfor side effects and ignoring the result. It works, but creates a throwaway array and hides intent. - Using
forEachand pushing into an outer array to build a result. That is exactly whatmapis for. - Forgetting to return inside
mapwith 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];23// map: produce a new array4const doubled = prices.map((p) => p * 2);5console.log(doubled); // [20, 40, 60]67// forEach: side effects only, returns undefined8const result = prices.forEach((p) => console.log("price", p));9console.log(result); // undefined1011// Anti-pattern: building an array with forEach12const viaForEach = [];13prices.forEach((p) => viaForEach.push(p * 2));14console.log(viaForEach); // works, but map says it better1516// Common map bug: block body without return17const broken = prices.map((p) => {18 p * 2;19});20console.log(broken); // [undefined, undefined, undefined]2122// map chains, forEach cannot23const summary = prices24 .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.