Problem Statement
Compare forEach, map, filter, and reduce. When should you use each?
Explanation
These are the four most important array methods in JavaScript. Each serves a different purpose.
ForEach executes a function for each element but returns undefined. Use it for side effects like logging, updating DOM, or sending data. It does not create a new array. You cannot break out of forEach.
Map transforms each element and returns a new array of the same length. Use it when you need to convert or modify every element, like extracting properties, formatting data, or applying calculations. Original array stays unchanged.
Filter creates a new array containing only elements that pass a test. Use it to select items matching criteria, remove unwanted elements, or find all matches. Returns empty array if nothing matches.
Reduce accumulates array elements into a single value by applying a function. Use it for summing, finding max or min, flattening arrays, grouping data, or any operation combining all elements into one result. Takes accumulator and current value.
When to use what:
Use forEach for side effects without creating new array. Use map for transforming every element into new array. Use filter for selecting subset of elements. Use reduce for aggregating into single value.
All methods are chainable and promote functional programming by avoiding mutations.
Code Solution
SolutionRead Only
const numbers = [1, 2, 3, 4, 5];
// forEach - side effects, returns undefined
let sum1 = 0;
numbers.forEach(num => {
sum1 += num; // Updating external variable
});
console.log(sum1); // 15
// map - transform each, returns new array
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter - select elements, returns new array
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
// reduce - accumulate to single value
const sum2 = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum2); // 15
// Chaining methods
const result = numbers
.filter(num => num > 2) // [3, 4, 5]
.map(num => num * 2) // [6, 8, 10]
.reduce((acc, num) => acc + num, 0); // 24
console.log(result); // 24
// Real world example
const users = [
{ name: 'John', age: 17, active: true },
{ name: 'Jane', age: 25, active: true },
{ name: 'Bob', age: 30, active: false }
];
// Get names of active adult users
const activeAdultNames = users
.filter(user => user.active && user.age >= 18)
.map(user => user.name);
console.log(activeAdultNames); // ['Jane']