On this page
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. Unlikemapandfilter,reducedoes 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.
undefinedas the explicit initial value must be used — hencearguments.length.- Sparse arrays: holes are skipped, including when looking for the starting element.
[, 1, 2].myReduce(f)starts with1. - 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
lengthonce at the start, so elements added later are not visited. Cachinglengives the same behaviour.
Follow-ups
-
Write
mapandfilterusing only yourreduce. Worked through in its own section below. -
Implement
pipeandcompose.piperuns functions left to right withreduce;composeruns them right to left withreduceRight.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?
thismust be the array the method is called on, and an arrow function has noargumentsobject 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 andout.pushfails on a number. - Return the accumulator from every call. Whatever the callback returns is the next
out. Forget thereturnandoutisundefinedon the second element.pushreturns the new length, not the array, soreturn 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
indexandarrayto the user’s callback, and usecb.call(thisArg, …), so the result behaves like the realmapandfilter. - Holes.
reduceskips holes, soout.pushin themapversion would close them up. Starting fromnew Array(this.length)and assigningout[i]keeps each result at its original index, as the built-inmapdoes.
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 — breaksreduce(fn, 0).- Starting the loop at index 0 when no initial value was passed, which counts the first element twice.
- Returning
undefinedfor an empty array instead of throwing. - Passing
thisArgto the callback —reducehas no such parameter. - In
reduceRight, looping whilei > 0and missing index 0.
Related
- Concepts: reduce polyfill in the JavaScript track.
- Previous: forEach, map and filter.
- Next: find, findIndex, some and every.