Skip to content
jshacks.dev
Functions

Implement Array.prototype.reduce From Scratch in JavaScript

Implement Array.prototype.reduce from scratch in JavaScript with and without an initial value, empty arrays, holes, errors and the exact callback arguments.

8 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, npm and TypeScript logos.

reduce folds an array into a single value by calling a function with an accumulator and each element in turn. It is the method that most people use least confidently and most interviewers like, because its edge cases are real: what happens without an initial value, on an empty array, on a sparse array, and what the callback receives. This post implements reduce on Node.js 24 in stages, shows the output for each edge case and finishes with the matching reduceRight, tests and the points to say aloud. If you have just read implementing map, the iteration rules are the same, and the new part is the accumulator.

What reduce does

array.reduce(callback, initialValue) starts with an accumulator. For each element, left to right, it calls callback(accumulator, element, index, array) and stores the return value as the new accumulator. At the end it returns the accumulator. If you pass initialValue, the accumulator starts as that value and the first call receives the first element. If you omit it, the accumulator starts as the first element, and the first call receives the second element.

The version with an initial value

JavaScript
Array.prototype.myReduce = function (callback, initialValue) {
  let accumulator = initialValue;

  for (let i = 0; i < this.length; i += 1) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
};

console.log([1, 2, 3, 4].myReduce((sum, n) => sum + n, 0));
console.log(["a", "b", "c"].myReduce((acc, ch, i) => ({ ...acc, [ch]: i }), {}));
Text
10
{ a: 0, b: 1, c: 2 }

The callback receives four arguments, as in map, with the accumulator first. That is the difference people forget: the element is the second parameter and the index the third. The second example builds an object from the array, which is the typical use beyond summing.

Without an initial value

When no initial value is given, the first element becomes the accumulator and the loop starts at index 1. This is where a naive implementation breaks, because undefined is a legitimate initial value, so you cannot detect "not provided" by checking the value. You must check the number of arguments.

JavaScript
Array.prototype.myReduce = function (callback, ...rest) {
  const hasInitial = rest.length > 0;
  let accumulator = rest[0];
  let start = 0;

  if (!hasInitial) {
    accumulator = this[0];
    start = 1;
  }

  for (let i = start; i < this.length; i += 1) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
};

console.log([5, 3, 8].myReduce((max, n) => (n > max ? n : max)));
console.log([1, 2, 3].myReduce((sum, n) => sum + (n ?? 0), undefined));
console.log([1, 2, 3].myReduce((acc, n) => `${acc}${n}`, undefined));
Text
8
NaN
undefined123

The first call finds the maximum without a start value, and the callback runs twice, for 3 and 8. The second shows that undefined passed explicitly counts as an initial value: undefined + 1 is NaN. The third prints undefined123, because the template string turns the initial undefined into the text undefined. A check like initialValue === undefined would have treated both calls as "no initial value" and returned different answers, which is the bug the rest parameter avoids. An alternative is arguments.length, which works in a regular function.

The empty array

With no elements and no initial value, there is nothing to start with, and the real reduce throws a TypeError.

JavaScript
try {
  [].reduce((a, b) => a + b);
} catch (error) {
  console.log(error.name, "|", error.message);
}

console.log([].reduce((a, b) => a + b, 0));
Text
TypeError | Reduce of empty array with no initial value
0

With an initial value, an empty array returns it untouched, and the callback is never called. This is why the advice to always pass an initial value is good: a reduce over data that might be empty works the same for every length. The wording of the error message belongs to the engine, so match the type and not the text in tests.

JavaScript
Array.prototype.myReduce = function (callback, ...rest) {
  if (typeof callback !== "function") {
    throw new TypeError(`${String(callback)} is not a function`);
  }

  const length = this.length >>> 0;
  let index = 0;
  let accumulator;

  if (rest.length > 0) {
    accumulator = rest[0];
  } else {
    while (index < length && !(index in this)) {
      index += 1;
    }

    if (index >= length) {
      throw new TypeError("Reduce of empty array with no initial value");
    }

    accumulator = this[index];
    index += 1;
  }

  for (; index < length; index += 1) {
    if (index in this) {
      accumulator = callback(accumulator, this[index], index, this);
    }
  }

  return accumulator;
};

try {
  [].myReduce((a, b) => a + b);
} catch (error) {
  console.log(error.name);
}

console.log([, , 4, , 6].myReduce((a, b) => a + b));
console.log([1, , 3].myReduce((sum, n, i) => sum + n * i, 0));
Text
TypeError
10
6

This version is closer to the specification. Without an initial value, it skips leading holes to find the first real element, and throws if there is none. In the loop, it skips holes, as map does. So [, , 4, , 6] starts with 4 and adds 6, giving 10. The last example multiplies each present element by its index: 0 + 1*0 + 3*2 is 6, and the hole at index 1 never reaches the callback. Reading length once at the start fixes the visited range, as in map.

Using the index and the array

Because the callback gets the index and the array, a few tricks are possible. You can compute a running average, or detect the last element.

JavaScript
const average = [4, 8, 6].myReduce((sum, n, i, array) => {
  const total = sum + n;
  return i === array.length - 1 ? total / array.length : total;
}, 0);

console.log(average);
Text
6

The sum is 18, and on the last index the callback returns the total divided by the length. It works, and it is clever in the wrong way: a reader has to see that the return type changes on the last step. Computing the average after the reduce is clearer. The sample is a good example of using the arguments without doing it.

reduceRight

reduceRight is the same algorithm from the last index down to zero. Without an initial value, it starts with the last element.

JavaScript
Array.prototype.myReduceRight = function (callback, ...rest) {
  const length = this.length >>> 0;
  let index = length - 1;
  let accumulator;

  if (rest.length > 0) {
    accumulator = rest[0];
  } else {
    while (index >= 0 && !(index in this)) {
      index -= 1;
    }

    if (index < 0) {
      throw new TypeError("Reduce of empty array with no initial value");
    }

    accumulator = this[index];
    index -= 1;
  }

  for (; index >= 0; index -= 1) {
    if (index in this) {
      accumulator = callback(accumulator, this[index], index, this);
    }
  }

  return accumulator;
};

console.log(["a", "b", "c"].myReduceRight((acc, ch) => acc + ch));
console.log(["a", "b", "c"].myReduce((acc, ch) => acc + ch));
Text
cba
abc

The right fold builds the string backwards. It is what you use for function composition, where the last function must run first, as described in implementing compose.

Reduce is not always the right tool

Many reduce calls would be clearer as something else. Summing is a good fit. Building an object with a spread in every step is a trap: each step copies the accumulator, so the total work grows with the square of the number of keys.

JavaScript
const entries = [["a", 1], ["b", 2], ["c", 3]];

const slow = entries.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
const fast = Object.fromEntries(entries);

console.log(slow, fast);
Text
{ a: 1, b: 2, c: 3 } { a: 1, b: 2, c: 3 }

Object.fromEntries does the same in one pass. Likewise Math.max(...numbers) and Array.prototype.some replace reductions that only find a maximum or test a condition. Use reduce when the result is a different shape from the elements and no more specific method exists.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("myReduce handles initial values", () => {
  assert.equal([1, 2, 3].myReduce((a, b) => a + b, 10), 16);
  assert.equal([1, 2, 3].myReduce((a, b) => a + b), 6);
  assert.equal([].myReduce((a, b) => a + b, "start"), "start");
});

test("myReduce throws on an empty array without an initial value", () => {
  assert.throws(() => [].myReduce((a, b) => a + b), TypeError);
});

test("myReduce passes index and array", () => {
  const seen = [];

  [10, 20].myReduce((acc, value, index, array) => {
    seen.push([index, array.length]);
    return acc;
  }, 0);

  assert.deepEqual(seen, [[0, 2], [1, 2]]);
});
Text
ℹ tests 3
ℹ pass 3
ℹ fail 0

Common mistakes with reduce

The most frequent bug is a callback that does not return the accumulator on every path. A branch that falls off the end returns undefined, and the next step sees undefined as the accumulator, so the failure shows up one element later and far from its cause. Write the return as the last line of the callback, and prefer a single expression over an if with several returns when you can.

The second is mutating an accumulator that is shared between calls. An array or object created outside the function and passed as the initial value is reused if the function runs again. Create the initial value inside the function that calls reduce, so each call starts fresh. The third is using reduce for control flow, such as stopping at the first match. A reduce cannot stop early, so it visits every element even after the answer is known, and some, find or a loop is the better tool.

Finally, watch the types. A reducer whose accumulator changes type between steps, a number at the start and an object at the end, is hard to read and impossible to type well in TypeScript. Keep the accumulator the same type throughout, and convert at the end if you must.

How to present it

Say the two modes first, with and without an initial value, because most mistakes come from mixing them. Write the version with an initial value in half a minute. Then ask the interviewer whether you may handle the case with no initial value, and use arguments.length or a rest parameter to detect it, explaining why a check against undefined is wrong. The empty array error and the hole skipping are the last refinements, and they are worth adding only if time allows.

If asked for the complexity, answer that it is linear in the number of elements, with one callback call per element, and that the real cost depends on the callback: a callback that copies the accumulator makes the whole thing quadratic.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.