How to use map, filter, and reduce in JavaScript
· Category: JavaScript
Short answer
map transforms each element, filter selects elements matching a condition, and reduce aggregates all elements into a single value.
Steps
- Transform with
map:javascript const doubled = [1, 2, 3].map(n => n * 2); // [2, 4, 6] - Select with
filter:javascript const evens = [1, 2, 3, 4].filter(n => n % 2 === 0); // [2, 4] - Aggregate with
reduce:javascript const sum = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0); // 10 - Chain them together:
javascript const total = items .filter(i => i.active) .map(i => i.price) .reduce((a, b) => a + b, 0);
Tips
- Always provide an initial value to
reduceto avoidTypeErroron empty arrays. - Use
maponly when you need a new array; useforEachfor side effects.
Common issues
- Mutating the accumulator in
reducewithout returning it causes incorrect results. - Chaining on very large arrays creates intermediate arrays; consider a
for...ofloop for performance-critical paths.