JavaScript Interview Question #41

What is the difference between map() and forEach()?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

map executes a callback for each element and returns a new array containing the callback results. forEach executes a callback for each element but returns undefined.

Detailed Explanation

map executes a callback for each element and returns a new array containing the callback results. forEach executes a callback for each element but returns undefined.

Use map when transforming data into a new array. Use forEach when the purpose is a side effect such as logging or updating an external operation. Using map only for side effects creates an unnecessary result array and obscures intent.

Code Example

const numbers = [1, 2, 3];

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]

numbers.forEach(n => {
    console.log(n);
});