JavaScript · The language round
What is the difference between forEach and map?
Short answer
map returns a new array containing the result of each callback. forEach returns undefined and is meant for side effects. Neither one can be stopped with break.
The methods look similar because both visit every element, but their contracts are different. Choosing the wrong one usually produces an accidental undefined or a loop that cannot be exited early.
const values = [1, 2, 3];
const doubled = values.map((value) => value * 2);
const sideEffect = values.forEach((value) => console.log(value));
console.log(doubled); // [2, 4, 6]
console.log(sideEffect); // undefinedWhen to use each
- Use
mapwhen you need a new array with one output per input - Use
forEachwhen you only need to perform an action, such as logging or updating an external store - Use
for...ofwhen you needbreak,continueorawaitinside the loop - Use
someoreverywhen you need to stop as soon as the answer is known
Returning a value from a forEach callback does not build an array. That value is discarded, which is a common source of bugs when someone expects forEach to behave like map.
const ids = [];
[1, 2, 3].forEach((id) => {
ids.push(id * 10);
});
console.log(ids); // [10, 20, 30]map expresses the transformation more directly.forEach skips holes in sparse arrays. map also preserves the holes, while Array.from can fill them.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why can't you `break` out of `forEach`?
- 2Can `forEach` await an async callback?
- 3What does `map` return if the callback returns nothing?
- 4When would you choose `for...of` over both?
Say it in the interview
map transforms each element and returns a new array of the same length. forEach visits each element for side effects and returns undefined. Neither supports break, so if I need early exit I use for...of or some. I choose map when the result is the point, and forEach when I only need to perform an action such as logging or updating an external store.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.