The Key Difference
The fundamental difference is simple: map() returns a new array, while forEach() returns undefined.
// map() - returns new array
const doubled = [1, 2, 3].map(x => x * 2);
console.log(doubled); // [2, 4, 6]
// forEach() - returns undefined
const result = [1, 2, 3].forEach(x => console.log(x));
console.log(result); // undefined
When to Use map()
Use map() when you need to transform data:
- Converting data formats
- Extracting specific properties from objects
- Applying calculations to each element
- Creating a new array based on existing data
// Perfect use case for map()
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
const names = users.map(user => user.name);
// ['John', 'Jane']
When to Use forEach()
Use forEach() when you need side effects:
- Logging or debugging
- Updating external variables
- DOM manipulation
- Making API calls for each item
// Perfect use case for forEach()
const items = document.querySelectorAll('.item');
items.forEach(item => {
item.classList.add('active');
});
Common Mistakes
1. Using map() but ignoring the result
// BAD - map() creates array that's never used
users.map(user => console.log(user.name));
// GOOD - use forEach() for side effects
users.forEach(user => console.log(user.name));
2. Trying to break out of forEach()
// forEach() cannot be stopped
// Use for...of or some() instead
for (const item of items) {
if (condition) break;
}
Performance Comparison
Both methods have similar performance for most use cases. However:
- map() allocates memory for a new array
- forEach() is slightly more memory-efficient when you don't need the result
- For very large arrays, consider using a traditional for loop
Chaining
map() can be chained with other array methods:
const result = numbers
.filter(n => n > 0)
.map(n => n * 2)
.reduce((sum, n) => sum + n, 0);
forEach() cannot be chained (returns undefined).
Summary Table
| Feature | map() | forEach() |
|---|---|---|
| Returns | New array | undefined |
| Chainable | Yes | No |
| Use for | Transformation | Side effects |
| Can break | No | No |
Conclusion
- Use map() when you need to transform data and use the result
- Use forEach() when you need to do something with each element but don't need a new array
- When in doubt, ask: "Do I need the result as an array?" If yes, use map().