ForgeFrontend — Prepare, Practice, Crack
Secure checkout
Lifetime access
Instant Drive delivery
Free updates forever

Prepare · Practice · Crack

map vs forEach in JavaScript

Both loop over an array, but they exist for different jobs — and picking the wrong one is a common code-review note.

The difference

map builds and returns a NEW array of the same length from each item's return value, so it's chainable and non-mutating. forEach returns undefined and just runs a callback per item — for side effects. Use map to transform, forEach for side effects.

[1, 2, 3].map(n => n * 2);       // [2, 4, 6]
[1, 2, 3].forEach(n => save(n)); // undefined

Which to use

If you want a transformed array back, use map (and you can chain .filter/.reduce after it). If you only need to do something per item and don't need a result, use forEach — but you can't break out of either; use for...of when you need break.

Master arrays & higher-order functions

map, filter, reduce, mutation gotchas and the array questions interviewers ask — in the JavaScript Interview Kit.

⚡ Get the JavaScript Interview Kit → ₹299

Frequently asked questions

Can I break out of map or forEach?
No — neither supports break/continue. Use a for...of loop (or some/every) when you need to stop early.
Is map slower than forEach?
Negligibly, and it allocates a new array. Choose based on intent (transform vs side effect), not micro-performance.

Full kit

JavaScript Interview Kit · ₹299

Get it →