JavaScript forEach vs map - When to Use Which
Detailed comparison of Array.forEach() and map(). Learn when to use each, performance differences, and why map should not be used for side effects. Free reference.
Detailed Explanation
forEach() vs map()
Both iterate over every element, but they serve fundamentally different purposes.
Array.forEach()
Executes a function for each element. Returns undefined. Used for side effects.
const nums = [1, 2, 3];
nums.forEach(n => console.log(n));
// Prints: 1, 2, 3
// Returns: undefined
Array.map()
Executes a function for each element. Returns a new array of results. Used for transformations.
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
// doubled: [2, 4, 6]
Key Differences
| Feature | forEach | map |
|---|---|---|
| Returns | undefined |
New array |
| Chainable | No | Yes |
| Use case | Side effects | Transformations |
| Can break early? | No* | No |
*To break early from iteration, use a for...of loop or some()/every().
Anti-Patterns
Using map for side effects (bad):
// BAD — creates and discards an array
items.map(item => {
saveToDatabase(item);
});
// GOOD — use forEach for side effects
items.forEach(item => {
saveToDatabase(item);
});
Using forEach to build an array (bad):
// BAD — manual accumulation
const results = [];
items.forEach(item => {
results.push(transform(item));
});
// GOOD — use map
const results = items.map(transform);
Performance
In practice, the performance difference between forEach and map is negligible for most use cases. The main consideration is:
- map allocates a new array, so if you do not need the result, forEach uses less memory
- Neither can be broken early — for that, use
for...of
When to Use Neither
For simple iteration where you might need break or continue:
for (const item of items) {
if (item.done) break;
process(item);
}
Use Case
Use map() when you need to produce a new array from an existing one (data transformation, React rendering). Use forEach() when you need to perform actions with each element but do not need a result array (logging, saving to database, updating the DOM).