Map vs ForEach
You'll learn when to choose map for transformations and when forEach is the right tool for side effects.
The Core Difference
Both map and forEach iterate over arrays, but they have fundamentally different purposes:
maptransforms data and returns a new array containing the resultsforEachexecutes code for each element but returnsundefined(used only for side effects)
Think of map like a factory assembly line: raw materials go in, transformed products come out. forEach is like a supervisor walking down the line checking each item—they observe and react, but don't produce anything new.
When to Use Map
Use map when you need to transform each element and collect the results:
const prices = [10, 20, 30];
const doubled = prices.map(price => price * 2);
// [20, 40, 60] - new array created
You're creating something new based on existing data.
When to Use ForEach
Use forEach when you need to do something with each element without creating a new array:
const prices = [10, 20, 30];
prices.forEach(price => {
console.log(`Price: $${price}`); // side effect: logging
});
// forEach returns undefined - we're not building anything
Common forEach use cases: logging, updating the DOM, sending network requests, or modifying external variables.
The Wrong Tool
Avoid using forEach when you need a transformed array—you'd have to manually push to an external array, which is verbose and error-prone. Similarly, don't use map just for side effects; ignoring its returned array is wasteful and confusing.
Key Takeaway: Use map when you need a new transformed array; use forEach when you only need side effects like logging or DOM updates. Let the return value guide your choice.