Array.prototype.reduce()
Combines every array element into a single accumulated result, using a callback and a starting value.
array.reduce((accumulator, element) => newAccumulator, initialValue)
Purpose
reduce builds up a single result — a sum, an object, another array, anything — by calling a
callback once per element, each time handing forward an accumulated value.
Syntax
const cart = [
{ name: 'Book', price: 12.5, qty: 2 },
{ name: 'Pen', price: 1.5, qty: 3 },
];
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
// 29.5
The callback’s first parameter (sum above) is the accumulator — whatever the previous call
returned, or initialValue on the very first call. The callback’s return value becomes the
accumulator for the next call.
Behavior notes
- Omitting
initialValueuses the array’s first element as the starting accumulator and begins iterating from the second element — legal, but produces aTypeErroron an empty array. Always passing an explicitinitialValueavoids that edge case. - The accumulator doesn’t have to be a number — building an object, a
Map, or another array withreduceare all common (array.reduce((obj, item) => ({ ...obj, [item.id]: item }), {})groups an array into a lookup object, for example). reduceis the most general of the array iteration methods —mapandfiltercould each be written usingreduce, though the dedicated methods read more clearly when they fit the shape of the problem.
Common mistakes
- Forgetting
initialValueand being surprised by aTypeErroron an empty array, or by the callback running one fewer time than expected. - Mutating and returning the same object/array across iterations instead of building a fresh
accumulator each time — usually works by accident, but obscures what
reduceis actually doing and can cause bugs if the initial value is reused elsewhere.
Runtime notes
Standard Array.prototype method, identical across every current browser and Node version.