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

  1. Transform with map: javascript const doubled = [1, 2, 3].map(n => n * 2); // [2, 4, 6]
  2. Select with filter: javascript const evens = [1, 2, 3, 4].filter(n => n % 2 === 0); // [2, 4]
  3. Aggregate with reduce: javascript const sum = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0); // 10
  4. 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 reduce to avoid TypeError on empty arrays.
  • Use map only when you need a new array; use forEach for side effects.

Common issues

  • Mutating the accumulator in reduce without returning it causes incorrect results.
  • Chaining on very large arrays creates intermediate arrays; consider a for...of loop for performance-critical paths.