On this page
Tracks

Polyfill: reduce and reduceRighthigh-yield

Last reviewed 6 Oct 2026

Problem

Implement myReduce and myReduceRight on Array.prototype, matching the built-ins:

[1, 2, 3].myReduce((sum, x) => sum + x, 0); // 6
[1, 2, 3].myReduce((sum, x) => sum + x); // 6 (no initial value)
['a', 'b', 'c'].myReduceRight((s, x) => s + x, ''); // 'cba'
['a', 'b', 'c'].myReduceRight((s, x) => s + x); // 'cba' (no initial value)

Clarifying questions

  • What does the callback receive? (accumulator, element, index, array).
  • Is the initial value optional? Yes. Without it, the first element (the last one for reduceRight) becomes the accumulator.
  • What should happen on an empty array with no initial value? Throw a TypeError.
  • Should holes in sparse arrays ([1, , 3]) be skipped? Yes — the built-ins skip them.
  • Is there a thisArg? No. Unlike map and filter, reduce does not take one.

Approach

Keep one value, the accumulator, and replace it with the callback’s result for every element. The only real decision is where the accumulator starts:

  • An initial value was passed: start with it and visit every element.
  • No initial value: the first existing element becomes the accumulator and the loop starts after it. If there is no element at all, throw.

Check arguments.length rather than initial === undefined, because undefined is a legitimate initial value. reduceRight is the same logic walking from the last index down to 0.

Step-by-step build

Step 1 — myReduce with an initial value

Array.prototype.myReduce = function (cb, initial) {
let acc = initial;
for (let i = 0; i < this.length; i++) {
if (i in this) acc = cb(acc, this[i], i, this);
}
return acc;
};

Step 2 — support a missing initial value

Array.prototype.myReduce = function (cb, initial) {
let i = 0;
let acc = initial;
if (arguments.length < 2) {
while (i < this.length && !(i in this)) i++; // find the first real element
if (i >= this.length) throw new TypeError('Reduce of empty array with no initial value');
acc = this[i++];
}
for (; i < this.length; i++) {
if (i in this) acc = cb(acc, this[i], i, this);
}
return acc;
};

Step 3 — myReduceRight

Mirror every index: start at length - 1, search downwards for the first real element, and loop while i >= 0.

Array.prototype.myReduceRight = function (cb, initial) {
let i = this.length - 1;
let acc = initial;
if (arguments.length < 2) {
while (i >= 0 && !(i in this)) i--; // find the last real element
if (i < 0) throw new TypeError('Reduce of empty array with no initial value');
acc = this[i--];
}
for (; i >= 0; i--) {
if (i in this) acc = cb(acc, this[i], i, this);
}
return acc;
};

Step 4 — validate the callback and read the length once

if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
const len = this.length;

Final code

Array.prototype.myReduce = function (cb, initial) {
if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
const len = this.length;
let i = 0;
let acc = initial;
if (arguments.length < 2) {
while (i < len && !(i in this)) i++;
if (i >= len) throw new TypeError('Reduce of empty array with no initial value');
acc = this[i++];
}
for (; i < len; i++) {
if (i in this) acc = cb(acc, this[i], i, this);
}
return acc;
};
Array.prototype.myReduceRight = function (cb, initial) {
if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
let i = this.length - 1;
let acc = initial;
if (arguments.length < 2) {
while (i >= 0 && !(i in this)) i--;
if (i < 0) throw new TypeError('Reduce of empty array with no initial value');
acc = this[i--];
}
for (; i >= 0; i--) {
if (i in this) acc = cb(acc, this[i], i, this);
}
return acc;
};

Edge cases

  • An empty array with no initial value throws; with an initial value it returns that value and never calls the callback.
  • A single element with no initial value is returned as-is, and the callback is never called.
  • undefined as the explicit initial value must be used — hence arguments.length.
  • Sparse arrays: holes are skipped, including when looking for the starting element. [, 1, 2].myReduce(f) starts with 1.
  • An array of only holes with no initial value throws, the same as an empty array.
  • The callback pushes to the array while looping: the built-in reads length once at the start, so elements added later are not visited. Caching len gives the same behaviour.

Follow-ups

  • Write map and filter using only your reduce. Worked through in its own section below.

  • Implement pipe and compose. pipe runs functions left to right with reduce; compose runs them right to left with reduceRight.

    const pipe = (...fns) => (x) => fns.myReduce((v, fn) => fn(v), x);
    const compose = (...fns) => (x) => fns.myReduceRight((v, fn) => fn(v), x);
  • Why not use arrow functions for the polyfills? this must be the array the method is called on, and an arrow function has no arguments object of its own.

Write map and filter using only reduce

A common twist to check you understand the accumulator. The accumulator is the output array: start it empty, add to it for each element, and return it every time.

Array.prototype.myMapViaReduce = function (cb, thisArg) {
return this.myReduce((out, x, i, arr) => {
out[i] = cb.call(thisArg, x, i, arr);
return out;
}, new Array(this.length));
};
Array.prototype.myFilterViaReduce = function (cb, thisArg) {
return this.myReduce((out, x, i, arr) => {
if (cb.call(thisArg, x, i, arr)) out.push(x);
return out;
}, []);
};
[1, 2, 3].myMapViaReduce((x) => x * 2); // [2, 4, 6]
[1, 2, 3, 4].myFilterViaReduce((x) => x % 2 === 0); // [2, 4]

The points an interviewer looks for:

  • Pass the initial value. Without [], the first element becomes the accumulator and out.push fails on a number.
  • Return the accumulator from every call. Whatever the callback returns is the next out. Forget the return and out is undefined on the second element. push returns the new length, not the array, so return out.push(x) is wrong too.
  • Mutate the accumulator instead of copying it. [...out, x] works but copies the array on every step, which is O(n²). The accumulator is a new array that nobody else holds, so pushing to it is safe.
  • Forward index and array to the user’s callback, and use cb.call(thisArg, …), so the result behaves like the real map and filter.
  • Holes. reduce skips holes, so out.push in the map version would close them up. Starting from new Array(this.length) and assigning out[i] keeps each result at its original index, as the built-in map does.

The inner callbacks are arrow functions on purpose: they need cb and thisArg from the outer function.

Common mistakes

  • if (!initial) instead of checking whether it was passed — breaks reduce(fn, 0).
  • Starting the loop at index 0 when no initial value was passed, which counts the first element twice.
  • Returning undefined for an empty array instead of throwing.
  • Passing thisArg to the callback — reduce has no such parameter.
  • In reduceRight, looping while i > 0 and missing index 0.