Table of Contents

The JavaScript Array reduce() method processes array elements and combines them into one accumulated result. That result can be a number, string, object, array, or another value. A reducer callback receives the current accumulator and element, then returns the accumulator for the next step. This guide adds practical examples for totals, averages, frequency counts, and choosing reduce() over simpler array methods.

Syntax and Formal Specification

The method signature is reduce(callbackFn, initialValue).

javascript
const prices = [10, 20, 30, 40];
const total = prices.reduce((acc, price) => acc + price, 0);
console.log(total);   // 100

Parameters

  • callbackFn — A function invoked for each element. It receives four arguments:

    • accumulator — The value returned from the previous callback invocation (or the initial value on the first call).

    • element — The current element being processed.

    • index — The integer index of the current element.

    • array — The array on which reduce() was called.

  • initialValue (optional) — The initial value of the accumulator. If provided, iteration starts at index 0. If omitted, the first array element is used as the initial accumulator, and iteration starts at index 1.

Return Value

The final accumulator value after all elements have been processed. The return type is whatever the reducer returns—anything from a primitive to an object to a function.

The Critical Difference: With vs Without initialValue

The most common source of bugs in reduce() is the optional initialValue. Its presence or absence changes behavior fundamentally.

With initialValue:

  • Iteration starts at index 0.

  • The accumulator starts as initialValue.

  • The reducer runs length times.

  • Empty arrays return initialValue (no error).

Without initialValue:

  • Iteration starts at index 1.

  • The accumulator starts as the first element (arr[0]).

  • The reducer runs length - 1 times.

  • Empty arrays throw a TypeError (“Reduce of empty array with no initial value”).

  • Single-element arrays return the element unchanged without invoking the callback.

javascript
// With initial value: safe for empty arrays
console.log([].reduce((a, b) => a + b, 0));   // 0 (no error)

// Without initial value: empty array throws
try {
  [].reduce((a, b) => a + b);
} catch (e) {
  console.log(e.constructor.name);   // "TypeError"
}

// Without initial value: single element returned as-is, no callback
console.log([5].reduce((a, b) => a + b));     // 5

// With initial value: callback invoked even for single element
console.log([5].reduce((a, b) => a + b, 10)); // 15

Always provide initialValue unless you have a specific reason not to. This avoids the empty-array error, makes the code self-documenting, and handles all input sizes uniformly.

Accumulator Mutation: A Cautionary Note

In reducers that accumulate into an object or array, mutating the accumulator in place is common for performance:

javascript
const words = ["apple", "apricot", "banana", "blueberry", "cherry"];

const grouped = words.reduce((acc, word) => {
  const letter = word[0];
  if (!acc[letter]) acc[letter] = [];
  acc[letter].push(word);   // mutate accumulator
  return acc;
}, {});

console.log(grouped);
// { a: ["apple", "apricot"], b: ["banana", "blueberry"], c: ["cherry"] }

This is efficient and idiomatic in JavaScript. However, in strict functional programming (and some state management libraries), returning a fresh accumulator each step is preferred:

javascript
const groupedImmutable = words.reduce((acc, word) => {
  const letter = word[0];
  return {
    ...acc,
    [letter]: [...(acc[letter] || []), word]
  };
}, {});

The immutable version is O(n²) for large arrays because each step copies the accumulated object. Use mutation for performance, immutable patterns for functional purity.

reduce() vs Manual Loops

reduce() is typically slightly slower than an explicit for loop because of the callback invocation overhead. For hot loops over large arrays, a manual loop can be 1.5×–2× faster:

javascript
const big = new Array(1_000_000).fill(1);

const t1 = performance.now();
const sumReduce = big.reduce((a, b) => a + b, 0);
console.log(performance.now() - t1);

const t2 = performance.now();
let sumLoop = 0;
for (let i = 0; i < big.length; i++) sumLoop += big[i];
console.log(performance.now() - t2);

console.log(sumReduce === sumLoop);   // true

For most application code, the readability of reduce() outweighs the micro-optimization. Reserve manual loops for performance-critical sections.

Early Termination: reduce() Cannot Short-Circuit

Unlike some(), every(), find(), and findIndex(), reduce() cannot terminate early. The reducer runs for every non-hole element, even after the accumulator has reached its final value. If early exit is needed, use a different method or wrap the reducer with a flag:

javascript
// Cannot short-circuit: reducer runs for all elements
const found = items.reduce((acc, item) => {
  if (acc !== null) return acc;   // "already found, skip"
  return item.id === targetId ? item : null;
}, null);

// Prefer find() when short-circuiting matters
const found2 = items.find(item => item.id === targetId);

For some practical cases, throwing from inside the reducer is a workaround, but it is ugly and slow.

Calculate totals and averages

A common use for reduce() is combining numeric values into a total. Start the accumulator at 0 so empty arrays are handled consistently.

const cart = [
  { item: "Book", price: 12 },
  { item: "Pen", price: 3 },
  { item: "Bag", price: 25 }
];

const total = cart.reduce((sum, product) => sum + product.price, 0);
console.log(total); // 40

The same pattern can calculate an average, but the empty-array case needs a deliberate result because dividing by zero does not produce a useful average.

const scores = [80, 90, 100];
const average = scores.length
  ? scores.reduce((sum, score) => sum + score, 0) / scores.length
  : 0;

console.log(average); // 90

Providing the starting sum of 0 also makes it clear that the accumulator is numeric, even when the input array contains no values.

Count values with an accumulator object

reduce() can build a summary object while scanning a list. For example, the callback can count how many times each label appears. Starting with Object.create(null) gives the accumulator no inherited property names.

const colors = ["blue", "red", "blue", "green", "red", "blue"];

const counts = colors.reduce((result, color) => {
  result[color] = (result[color] || 0) + 1;
  return result;
}, Object.create(null));

console.log(counts);
// { blue: 3, red: 2, green: 1 }

The object is the accumulator: each step updates one count and returns the same object for the next callback. This resembles the grouping example in the existing article, but records a count rather than storing lists of matching words.

Know when reduce() is the right tool

reduce() is flexible, but using it for every array operation can make code harder to read. Prefer a method whose result matches your goal:

  • Use map() to transform each element into a corresponding output.
  • Use filter() to keep the elements that pass a condition.
  • Use find() to get the first matching element, or some() to check whether any item matches.
  • Use reduce() when you are combining many elements into a single result, such as a total, summary object, or grouped structure.

A simple sum is a natural reduction. A chain of unrelated conditions and nested accumulator updates may be clearer as separate steps or a loop. Choose the version that lets another reader understand what each element contributes.

How reduce() handles sparse arrays

reduce() skips empty slots in a sparse array, just as it skips indexes that do not exist. It still visits an explicit undefined value. If no initialValue is supplied, the method looks for the first present element to seed the accumulator; an array with no present elements throws a TypeError.

const sparse = [1, , 3];
const total = sparse.reduce((sum, value) => sum + value, 0);

console.log(total); // 4

The hole contributes nothing because the callback is not called for that position. If you need every index to participate, fill missing positions deliberately before reducing, or use a loop that checks the full index range.

Using reduce() with asynchronous work

reduce() does not wait for an async callback. If you pass an async function, each callback returns a Promise, so the accumulator becomes a Promise unless you explicitly await the previous result.

const values = [2, 4, 6];

const total = await values.reduce(async (sumPromise, value) => {
  const sum = await sumPromise;
  const adjusted = await getAdjustedValue(value);
  return sum + adjusted;
}, Promise.resolve(0));

This pattern runs each asynchronous step in sequence because the next reduction awaits the previous accumulator. If the operations are independent and should run concurrently, use Promise.all(values.map(...)) instead, then reduce the resolved values. Select the approach based on whether one step depends on the result of the previous step.