Array.prototype.reduce Polyfill

ArraysPolyfill

Implement Array.prototype.myReduce that behaves identically to the native reduce.

Function Signature:

Array.prototype.myReduce = function (callback, initialValue) { }

Requirements:

  • Throw TypeError if callback is not a function
  • When initialValue is provided: start accumulator at initialValue, iterate from index 0
  • When initialValue is not provided: first real element becomes accumulator, iterate from index 1
  • Calling on an empty array with no initialValue must throw TypeError
  • Skip holes in sparse arrays

Examples

Example 1
Input
[1, 2, 3, 4].myReduce((acc, cur) => acc + cur, 0)
Output
10
Explanation
Starts at 0, folds left: 0+1=1, 1+2=3, 3+3=6, 6+4=10.
Example 2
Input
[1, 2, 3].myReduce((acc, cur) => acc + cur)
Output
6
Explanation
No initial value: first element (1) is the accumulator, then 1+2=3, 3+3=6.
Example 3
Input
[].myReduce((acc, cur) => acc + cur)
Output
TypeError: Reduce of empty array with no initial value
Explanation
Empty array with no initial value must throw.

Constraints

  • Use `arguments.length >= 2` to detect whether initialValue was passed — not `=== undefined`
  • Do not use the native Array.prototype.reduce internally

Notes

  • `undefined` is a valid initial value a caller might pass intentionally

Hints

Read the full write-up for Array.prototype.reduce Polyfill
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it