Both forEach() and map() loop through array elements, but map() creates and returns a new array, while forEach() simply executes a function for each element without returning anything. Map is for transforms while forEach is for side effects; test immutability and return values.
Can you describe the main difference between Array.forEach() and Array.map() methods and why you would pick one versus the other?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The Core Idea
Both forEach() and map() are used to iterate over arrays, but they serve different purposes:
- forEach() is for performing side effects (like logging or updating variables). It doesn’t return anything useful.
- map() transforms data — it creates a new array based on what you return in each iteration.
Feature |
|
|
|---|---|---|
Return value |
| New array with transformed values |
Purpose | Execute side effects (e.g., log, mutate external state) | Transform data into a new array |
Mutates original array? | No (but can if you explicitly modify it) | No |
Chaining | No — returns undefined | Yes — returns a new array |
Typical use case | Logging, counters, DOM manipulation | Mapping API results, converting data |
Example: forEach()
Used when you want to do something for each element, not necessarily produce a new array.
const nums = [1, 2, 3];
nums.forEach(n => console.log(n * 2));
// Output:
// 2
// 4
// 6
// (forEach returns undefined)
Example: map()
Used when you want to transform each element and keep the results in a new array.
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
Common Mistake
Using map() just for its side effects. Since it expects you to return something, doing so wastes performance and memory.
If you’re not using the returned array, you probably meant forEach().
// ❌ Wrong: using map() for side effects only
numbers.map(n => console.log(n)); // just prints, no new array needed
// ✅ Correct:
numbers.forEach(n => console.log(n));
Practical scenario
Transform API data into UI rows: use map to return a new array, and forEach only for side effects.
Common pitfalls
- Expecting
forEachto return a transformed array. - Mutating the original array inside
map. - Ignoring return values and creating unused arrays.
map is declarative but allocates a new array. Test immutability and verify return values.Imagine sorting mail:
- forEach() → you open each envelope and read it.
- map() → you open each envelope, copy the letter, and build a new stack of letters — the transformed result.
- Use forEach() → when you want to iterate and perform an action (no return).
- Use map() → when you want to create a new array by transforming data.
If you need chaining or data transformation, always prefer map().