When to Use forEach vs map
You'll learn: How to choose between forEach and map based on whether you're performing side effects or transforming data.
At this point, you've learned both forEach and map, and they might seem interchangeable—both loop through arrays and execute a function on each element. But there's an important semantic difference that makes your code clearer when you use them correctly.
The Core Distinction
Use map when you want to transform an array into a new array. You care about the return values and want to collect them.
Use forEach when you want to perform side effects for each element. You're doing something (logging, updating external variables, modifying the DOM), but you don't need a new array.
Think of It This Way
mapis like a factory assembly line: raw materials go in, transformed products come outforEachis like a tour guide: you visit each stop to do something, but you're not building anything new
Examples in Plain English
Use map when:
- Converting temperatures from Celsius to Fahrenheit
- Extracting specific properties from objects
- Applying any transformation where you need the results
Use forEach when:
- Logging each element to the console
- Adding event listeners to DOM elements
- Updating a counter or accumulating values in an external variable
- Any action where the operation itself is the goal, not creating new data
Why This Matters
Using the right method signals your intent to other developers (and your future self). When someone sees map, they know a new array is being created. When they see forEach, they know side effects are happening.
Key Takeaway: Use map for transformations that return new arrays; use forEach for side effects where you don't need the return value.