By Rahul — Google Frontend Engineer
The One Rule
If you need the result array, use map(). If you do not, use forEach(). That is it. But let me show you why people get this wrong and what happens in production.
Core Difference
Common Mistakes
Mistake 1: Using map When You Do Not Need the Result
ESLint rule array-callback-return catches this. Enable it.
Mistake 2: Using forEach to Build an Array
Mistake 3: Trying to Break Out of forEach
Performance
In V8, for loop is fastest, forEach and map have similar overhead. For arrays under 10,000 items, the difference is negligible. For very large datasets, consider for loops or streaming approaches.
Async Gotcha
This is one of the most common production bugs. forEach does not respect async/await. The callback fires and forEach moves on immediately.
Best Practices
- Use
mapfor transformations (data in → data out) - Use
forEachfor side effects (logging, API calls, DOM mutations) - Never use
forEachwith async callbacks — usefor...oforPromise.allwithmap - Enable
array-callback-returnESLint rule
Summary
map transforms. forEach performs side effects. The async gotcha alone makes this worth understanding deeply.