Arrays
array.reduce()
Walks an array with an accumulator and returns a single final result.
Why it exists
Many questions about a list need one answer: the cart total, the most expensive item, how many orders are in each status. It's always the same technique — an accumulator plus a loop. reduce packages it as a method: you describe only "how to update the total with one item", and it does the walking and the passing of the total from step to step.
Where it's used
- Sums and totals: a cart, a receipt, total time.
- Counting: how often each word appears —
{ cat: 2, dog: 1 }. - Grouping and building objects from a list.
- Finding a maximum or minimum.
Syntax
array.reduce((total, item) => newTotal, startingValue)Examples
const prices = [120, 80, 45];
prices.reduce((total, p) => total + p, 0); // → 245const words = ["cat", "dog", "cat"];
words.reduce((counts, w) => {
counts[w] = (counts[w] ?? 0) + 1;
return counts;
}, {}); // → { cat: 2, dog: 1 }[3, 9, 2].reduce((max, n) => (n > max ? n : max)); // → 9[].reduce((a, b) => a + b, 0); // → 0Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
reduce calls the callback for each item in order. The callback's first argument is the total so far, the second the current item. Whatever the callback returns becomes the total for the next step. After the last item, reduce returns the total.
The starting value (reduce's second argument) is the total before the first step. Without it, the first item becomes the total and the walk starts at the second. On an empty array with no starting value, reduce throws a TypeError — so a starting value is almost always worth passing.
In essence, reduce is a loop with an accumulator, written as a method.
Traps
How it differs from…
for...ofloopA loop with an accumulator does the same and often reads more simply, especially with more than one step.
reduceis handy when the total is a short expression.array.map()map returns an array of the same length;
reducereturns one value of any type: a number, a string, an object.
When to pick something else
Practice
Lessons where this appears
- The conveyor at the fish factoryTale · Chapter 10 · map, filter, reduce
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- Comment counterLab · Chapter 13 · Recursion
- A cart classLab · Chapter 14 · this and classes
- The case of "0[object Promise]"Investigation · Chapter 16 · Async
- Order totalLab · Chapter 17 · Project: an online shop