Array map() vs forEach() in JavaScript: Key Differences
Direct Answer & Key Concept
The primary difference between map() and forEach() is that map() allocates and returns a new array containing transformed items, whereas forEach() executes a side effect for each element and returns undefined.
// Comparing map and forEach
const numbers = [1, 2, 3, 4];
// Transformation: map
const squares = numbers.map(n => n * n);
console.log("Squares:", squares); // [1, 4, 9, 16]
// Side Effect: forEach
let sum = 0;
numbers.forEach(n => { sum += n; });
console.log("Sum:", sum); // 10What is the difference between map() and forEach()?
Both Array.prototype.map() and Array.prototype.forEach() iterate through array elements from start to finish, calling a supplied callback function on each item. However, they serve fundamentally different architectural roles:
- Use
map()when your goal is to transform data and produce a new array without mutating the source data. - Use
forEach()when your goal is to execute side effects (such as logging, updating external variables, or triggering network requests) without needing a return value.
Detailed Comparison Table: map vs forEach
| Feature | Array.prototype.map() | Array.prototype.forEach() |
| :--- | :--- | :--- |
| Return Value | A new array of identical length | Always undefined |
| Primary Use Case | Pure data transformation | Performing external side effects |
| Chainability | Yes (.map().filter().reduce()) | No (returns undefined) |
| Mutates Original? | No (unless callback mutates elements) | No (unless callback mutates elements) |
| Can Break Early? | No | No (use for...of or some() instead) |
Code Comparison: Practical Examples
Using map() for Pure Transformation
const rawPrices = [19.99, 4.50, 100.00];
// map returns a new array; rawPrices remains unchanged
const formattedPrices = rawPrices.map(price => `$${price.toFixed(2)}`);
console.log(formattedPrices); // ["$19.99", "$4.50", "$100.00"]
Using forEach() for Side Effects
const usersToNotify = ["Alice", "Bob", "Charlie"];
// forEach performs an action; it returns undefined
usersToNotify.forEach(user => {
console.log(`Sending notification email to ${user}...`);
});
How to Break Early from Array Loops
Neither map() nor forEach() supports the break or continue statements. If your algorithm requires terminating early once a condition is satisfied:
- Use
for...ofloop: Supportsbreakandcontinuenatively. - Use
Array.prototype.some(): Terminates iteration as soon as a callback returns a truthy value. - Use
Array.prototype.find(): Stops searching immediately after locating the first match.
Common Mistakes with map and forEach
- Using map() without using its return value: Calling
arr.map(x => console.log(x))needlessly allocates a new array ofundefinedvalues in memory. UseforEach()instead. - Expecting forEach() to return data: Writing
const doubled = arr.forEach(x => x * 2)assignsundefinedtodoubled. - Attempting to use break inside forEach: Calling
breakinsideforEach()triggers a syntax error (SyntaxError: Illegal break statement).