JavaScript Array.prototype.reduce()

A detailed, beginner-friendly explanation with interactive step-by-step visualization.

What reduce does (in one sentence)

It iterates over an array and "reduces" it to a single value by running a callback that receives an accumulator and the current value on each step.

Quick syntax reminder

const result = array.reduce((accumulator, currentValue, currentIndex, array) => {
  // your logic
  return accumulator;
}, initialValue);

What each parameter means

  • accumulator — accumulates the result across iterations (start value = initialValue if provided).
  • currentValue — the current item being processed.
  • currentIndex — index of the current item (useful for position-aware logic).
  • array — the original array reduce was called on.

Golden rules

  1. Prefer providing initialValue — avoids subtle bugs (especially with empty arrays).
  2. If you need a single final value (sum, object, array), use reduce.
  3. For simple mapping or filtering use map or filter instead — they are more readable for common cases.
Tip: reduce is generic — you can produce numbers, strings, objects, arrays, or even promises (with care).

Output & Step Log

Run an example to see result and steps here.

Code used

// example code will appear here after running

Hand-traced example (Sum)

Array: [10, 20, 30] with initialValue = 0

Iterationaccumulator (before)currentValueaccumulator (after return)
10100 + 10 = 10
2102010 + 20 = 30
3303030 + 30 = 60

Final result: 60

Common patterns

Sum

const total = nums.reduce((acc, curr) => acc + curr, 0);

Count occurrences

const obj = arr.reduce((acc, val) => { acc[val] = (acc[val] || 0) + 1; return acc }, {});

Group by property

const grouped = items.reduce((acc, item) => { (acc[item.type] ||= []).push(item); return acc }, {});

Flatten (array of arrays)

const flat = arrays.reduce((acc, a) => acc.concat(a), []);

Why provide initialValue?

If you omit initialValue, the first array element becomes the accumulator and iteration starts from the second element. This can cause errors with empty arrays or when the accumulator must be a different type (object vs number).

// Dangerous when array may be empty
[].reduce((acc, curr) => acc + curr); // throws TypeError: Reduce of empty array with no initial value

// Safer
[].reduce((acc, curr) => acc + curr, 0); // 0