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.groupBynow 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
1const orders = [2 { customer: "Ada", total: 120 },3 { customer: "Linus", total: 80 },4 { customer: "Ada", total: 50 },5];67const revenue = orders.reduce((sum, o) => sum + o.total, 0);8console.log(revenue); // 250910// 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 }1617// Count words18const 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 }2122// Without an initial value, an empty array throws23try {24 [].reduce((a, b) => a + b);25} catch (e) {26 console.log(e.name); // TypeError27}2829// Compose functions with reduce30const 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.