The main difference between map(), forEach(), and reduce() is what they return and how they’re used to work with arrays.
🧭 1. forEach()
- Used to loop through each element of an array.
- It does not return anything (always
undefined). - Best when you just want to perform an action on each element.
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2);
});
// Output: 2, 4, 6
🧭 2. map()
- Also loops through each element.
- Returns a new array with the transformed values.
- Best when you want to create a new array from the old one.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
// Output: [2, 4, 6]
🧭 3. reduce()
- Reduces the entire array to a single value (number, string, object, etc.).
- Takes an accumulator and the current value.
- Useful for summing, multiplying, counting, or building new structures.
const numbers = [1, 2, 3];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);
// Output: 6
✅ In short:
forEach()→ just iterates (no return).map()→ transforms and returns a new array.reduce()→ combines all elements into a single result.