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 initialValue uses the array’s first element as the starting accumulator and begins iterating from the second element — legal, but produces a TypeError on an empty array. Always passing an explicit initialValue avoids that edge case.
  • The accumulator doesn’t have to be a number — building an object, a Map, or another array with reduce are all common (array.reduce((obj, item) => ({ ...obj, [item.id]: item }), {}) groups an array into a lookup object, for example).
  • reduce is the most general of the array iteration methods — map and filter could each be written using reduce, though the dedicated methods read more clearly when they fit the shape of the problem.

Common mistakes

  • Forgetting initialValue and being surprised by a TypeError on 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 reduce is 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.

Taught in these lessons

Related reference