JavaScript Reduce Explained: 12 Practical Examples
JavaScript reduce turns an array into a single value: a total, an object, a map or even a chain of promises. Learn how the accumulator works step by step, the patterns worth knowing, the empty array error, and when a plain loop is the better choice, with output from real runs.
- JavaScript reduce calls your function once per element, carrying an accumulator from one call to the next.
- Always pass an initial value. Without it, an empty array throws
TypeErrorand arrays of objects give wrong results. - Mutating the accumulator is fine and fast. Spreading it into a new object every step was about 90 times slower in our test.
- For simple grouping,
Object.groupByis now clearer than reduce.
map transforms every item and filter keeps some of them, but sometimes you need to boil a whole array down to one result: a cart total, a word count, an index by ID. That is the job of JavaScript reduce. It is the most flexible array method and also the most misunderstood, because the accumulator can be anything.
All examples were run on Node.js v24.22.1, and the output shown is what it printed. Need a refresher on the other array methods first? See our guide to JavaScript array methods.
What does reduce do in JavaScript?
Array.prototype.reduce() walks through an array from left to right. For each element it calls a reducer function with two main arguments: the value accumulated so far and the current element. Whatever the reducer returns becomes the accumulator for the next element. After the last element, reduce returns the final accumulator.
The result does not have to be a number. It can be a string, an array, an object, a Map or a promise. That is what makes reduce powerful, and also why it can become hard to read.
Reduce syntax
array.reduce((accumulator, currentValue, index, array) => {
// return the new accumulator
}, initialValue);
- accumulator: the running result.
- currentValue: the element being processed.
- index and array: optional, rarely needed.
- initialValue: the starting accumulator. Optional in theory, but you should almost always provide it.
How reduce works, step by step
We logged every call while summing [1, 2, 3] from an initial value of 0:
[1, 2, 3].reduce((acc, n, i) => {
console.log(`i=${i} acc=${acc} n=${n} -> ${acc + n}`);
return acc + n;
}, 0);
// i=0 acc=0 n=1 -> 1
// i=1 acc=1 n=2 -> 3
// i=2 acc=3 n=3 -> 6
Each line shows the accumulator going in and the value coming out. The returned 6 is the final result. If you ever get lost in a complex reducer, adding this one log line is the fastest way to see what is happening.
Examples 1 to 3: sum, max and average
const nums = [4, 8, 15, 16, 23, 42];
nums.reduce((acc, n) => acc + n, 0); // 108
nums.reduce((m, n) => (n > m ? n : m)); // 42
nums.reduce((acc, n, i, arr) => acc + n / arr.length, 0); // 18
Summing is the classic use. For a maximum, Math.max(...nums) is shorter, but it can throw a RangeError on very large arrays because of the argument limit, while reduce handles any size. The average example uses the fourth argument, the array itself, to divide as it goes.
Example 4: counting occurrences
const fruits = ["apple", "kiwi", "apple", "fig", "kiwi", "apple"];
const tally = fruits.reduce((t, f) => {
t[f] = (t[f] ?? 0) + 1;
return t;
}, {});
// { apple: 3, kiwi: 2, fig: 1 }
Start with an empty object and increment a key for each item. The ?? operator supplies 0 the first time a key appears. The same pattern counts words, status codes in a log file or votes in a poll.
Example 5: grouping objects
const orders = [
{ id: 1, city: "Pune", total: 250 },
{ id: 2, city: "Delhi", total: 120 },
{ id: 3, city: "Pune", total: 80 },
];
const byCity = orders.reduce((g, o) => {
(g[o.city] ??= []).push(o.id);
return g;
}, {});
// { Pune: [ 1, 3 ], Delhi: [ 2 ] }
Grouping used to be the top reason to reach for reduce. Modern JavaScript now has Object.groupBy(orders, o => o.city), which returned the same groups in our test (with full objects instead of IDs). Prefer it when your runtime supports it, and keep reduce for groupings that also aggregate.
Example 6: totals in a Map
const totals = orders.reduce(
(m, o) => m.set(o.city, (m.get(o.city) ?? 0) + o.total),
new Map()
);
console.log([...totals]); // [ [ 'Pune', 330 ], [ 'Delhi', 120 ] ]
Map.prototype.set returns the map itself, which makes it a natural one-line reducer. A Map keeps insertion order and allows non-string keys; our Map vs Object guide explains when that matters.
Examples 7 and 8: flattening and indexing
[[1, 2], [3], [4, 5]].reduce((a, b) => a.concat(b), []);
// [ 1, 2, 3, 4, 5 ]
const byId = orders.reduce((idx, o) => { idx[o.id] = o.city; return idx; }, {});
// { '1': 'Pune', '2': 'Delhi', '3': 'Pune' }
Flattening with reduce works, but arr.flat() is clearer today. Building a lookup object by ID is still a great reduce job: turn an array into an object once, then look items up instantly instead of calling find in a loop. Note that object keys become strings.
Example 9: composing functions
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const format = pipe(x => x + 1, x => x * 2, x => `#${x}`);
console.log(format(5)); // #12
Here the array holds functions, and the accumulator is the value passing through them: 5 becomes 6, then 12, then the string #12. This is how many middleware and data-pipeline helpers are built.
Example 10: running promises in sequence
const sleep = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
const results = await [1, 2, 3].reduce(async (p, n) => {
const out = await p;
out.push(await sleep(10, n * 10));
return out;
}, Promise.resolve([]));
// [ 10, 20, 30 ]
The accumulator is a promise, and each step waits for the previous one before starting. That makes the calls run one after another, useful for rate-limited APIs. A plain for...of loop with await does the same job more readably, as shown in our async/await guide, so treat this as a pattern to recognise in existing code.
Examples 11 and 12: why the initial value matters
[].reduce((a, b) => a + b);
// TypeError: Reduce of empty array with no initial value
[].reduce((a, b) => a + b, 0); // 0
const cart = [{ price: 5 }, { price: 7 }];
cart.reduce((a, b) => a + b.price); // '[object Object]7'
cart.reduce((a, b) => a + b.price, 0); // 12
Without an initial value, reduce uses the first element as the accumulator and starts from the second. On an empty array there is no first element, so it throws. On an array of objects, the first object becomes the accumulator and gets glued to a number as a string, a bug that passes silently. Always pass the initial value; it also documents the type of the result.
Tip: the initial value should be the same type as the result: 0 for sums, {} for lookups, [] for lists and new Map() for maps.
reduceRight and sparse arrays
["a", "b", "c"].reduceRight((acc, s) => acc + s, ""); // 'cba'
[1, , 3].reduce((acc) => acc + 1, 0); // 2
reduceRight works the same way but from the last element to the first. The second line shows that reduce skips holes in sparse arrays: three slots, but the callback ran only twice.
Performance: reduce vs loops
We timed each approach in Node.js 24 (best of five runs):
| Task | Time |
|---|---|
Sum 1,000,000 numbers with reduce |
9.90 ms |
Sum 1,000,000 numbers with for...of |
7.24 ms |
| Index 5,000 objects, spreading the accumulator | 10.87 ms |
| Index 5,000 objects, mutating the accumulator | 0.12 ms |
Reduce versus a loop is a small difference for sums. The big trap is (acc, o) => ({ ...acc, [o.id]: o }). It copies the whole accumulator on every step, so the work grows with the square of the array length. Mutating an accumulator you created yourself, as in the second index example, is safe and about 90 times faster here. The spread operator guide covers this cost in more detail.
When not to use reduce
- Simple transforms: use
maporfilter, which say what they do. - Grouping only: use
Object.groupByorMap.groupBy. - Flattening: use
flat()orflatMap(). - Early exit: reduce always visits every element; use
some,findor a loop withbreak. - Long multi-step reducers: if a reducer needs comments to explain it, a
for...ofloop is usually easier to review.
Python has the same idea in functools.reduce; compare the styles in our Python map and filter guide.
Final thoughts
JavaScript reduce is a single tool for turning many values into one. Pass an initial value every time, return the accumulator from every call, mutate your own accumulator instead of spreading it, and choose a clearer built-in when one exists. Used that way, reduce produces short, fast code for totals, tallies, lookups and pipelines.
Frequently asked questions
What does reduce return in JavaScript?
It returns the final value of the accumulator after the reducer has run on every element. That value can be a number, string, array, object, Map or promise.
Why do I get Reduce of empty array with no initial value?
You called reduce on an empty array without an initial value, so there is nothing to start from. Pass an initial value as the second argument, such as 0 or an empty object.
Is reduce slower than a for loop?
Slightly. In our Node.js 24 test, summing a million numbers took 9.90 ms with reduce and 7.24 ms with a for of loop. Copying the accumulator on every step is the real slowdown to avoid.
Can reduce return an object?
Yes. Pass an empty object as the initial value, add keys inside the reducer and return the object. This is common for counting items and building lookups by ID.
What is the difference between reduce and reduceRight?
reduce processes elements from first to last, while reduceRight processes them from last to first. Otherwise they take the same arguments and work the same way.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.