Q38 [Coding]: Write a custom polyfill for Array.prototype.reduce().

Array.prototype.myReduce = function(callback, initialValue) {
  let accumulator = initialValue;
  let startIndex = 0;
  if (accumulator === undefined) {
    if (this.length === 0) throw new TypeError('Reduce of empty array with no initial value');
    accumulator = this[0];
    startIndex = 1;
  }
  for (let i = startIndex; i < this.length; i++) {
    if (i in this) {
      accumulator = callback(accumulator, this[i], i, this);
    }
  }
  return accumulator;
};
Key Takeaways
  • Initializes accumulator to initialValue or array element index 0.
  • Sequentially processes callback updates across array elements.
Knowledge Check

What occurs if myReduce is called on an empty array without an initialValue parameter?