Home
← All questions

Polyfill for Array.prototype.reduce in JavaScript

EasyPremiumJavaScript

JavaScript interview practice: Implement reduce, handling the optional initial value edge cases.

Problem

Writing a polyfill for Array.prototype.reduce in JavaScript is a common frontend interview task because it checks whether you know the method's exact contract, especially the edge cases around the optional initial value.

Implement Array.prototype.myReduce(callback, initialValue) so that it behaves like the native Array.prototype.reduce.

Requirements

  • callback is called with (accumulator, currentValue, index, array) for each element, from left to right, and its return value becomes the next accumulator.
  • myReduce returns the final accumulator.
  • If initialValue is provided, it is the first accumulator and processing starts at index 0.
  • If initialValue is omitted, the first element is used as the first accumulator and processing starts at index 1.
  • An explicitly passed initialValue of undefined still counts as provided.
  • Calling it on an empty array with no initialValue throws a TypeError; with an initialValue, it returns that value without calling callback.
  • Throw a TypeError if callback is not a function.
  • Holes in sparse arrays are skipped, just like the native method.
  • Do not use the built-in reduce.

Example

[5, 10, 15].myReduce((acc, n) => acc + n, 100);  // 130
[2, 3, 4].myReduce((acc, n) => acc * n);         // 24
["a", "b"].myReduce((acc, s, i) => acc + s + i, ""); // "a0b1"
[].myReduce((acc, n) => acc + n, 0);             // 0
[].myReduce((acc, n) => acc + n);                // TypeError
[1, , 3].myReduce((acc, n) => acc + n);          // 4

Follow-ups

  • How would you implement myReduceRight?
  • Why is extending Array.prototype risky in production code?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium