What is the reduce() method?

reduce() walks an array and combines its elements into a single result (a number, string, object, array or anything else) by repeatedly calling a reducer function with an accumulator and the current element.

Signature

array.reduce((accumulator, element, index, array) => nextAccumulator, initialValue)

The value you return becomes the accumulator for the next element. The final accumulator is the result.

Always pass an initial value

Without one, reduce uses the first element as the starting accumulator and starts at index 1. That breaks when the array is empty (it throws a TypeError) and when the accumulator should be a different type from the elements (like building an object from an array of numbers).

Common uses

  • Totals and averages.
  • Building lookup objects: users.reduce((map, u) => ({ ...map, [u.id]: u }), {}).
  • Counting occurrences.
  • Grouping (though Object.groupBy now does this directly).
  • Running a list of functions in sequence (pipelines, promise chains).

When not to use it

reduce is powerful but can be hard to read. If map, filter, Object.groupBy, Object.fromEntries or a plain for...of expresses the idea more clearly, use that.

Performance tip

Spreading the accumulator on every step ({ ...acc, [key]: value }) copies it each time, which is O(n²). For large arrays, mutate the accumulator you created yourself (acc[key] = value; return acc;). That is safe because nothing else references it.

Code example

js
1const orders = [
2 { customer: "Ada", total: 120 },
3 { customer: "Linus", total: 80 },
4 { customer: "Ada", total: 50 },
5];
6
7const revenue = orders.reduce((sum, o) => sum + o.total, 0);
8console.log(revenue); // 250
9
10// Totals per customer: mutate our own accumulator (fast, still pure overall)
11const byCustomer = orders.reduce((acc, o) => {
12 acc[o.customer] = (acc[o.customer] ?? 0) + o.total;
13 return acc;
14}, {});
15console.log(byCustomer); // { Ada: 170, Linus: 80 }
16
17// Count words
18const words = "the cat and the hat".split(" ");
19const counts = words.reduce((acc, w) => acc.set(w, (acc.get(w) ?? 0) + 1), new Map());
20console.log(Object.fromEntries(counts)); // { the: 2, cat: 1, and: 1, hat: 1 }
21
22// Without an initial value, an empty array throws
23try {
24 [].reduce((a, b) => a + b);
25} catch (e) {
26 console.log(e.name); // TypeError
27}
28
29// Compose functions with reduce
30const pipe = (...fns) => (x) => fns.reduce((v, fn) => fn(v), x);
31console.log(pipe((x) => x + 1, (x) => x * 10)(4)); // 50

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app