Polyfill: Array.prototype.reduce

Difficulty: easy

Implement Array.prototype.reduce. This method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.

To avoid conflicts, implement it as Array.prototype.myReduce.

Example

[1, 2, 3].myReduce((prev, curr) => prev + curr, 0); // 6
[1, 2, 3].myReduce((prev, curr) => prev + curr, 4); // 10

More JS Coding

View all JS Coding →
JS CodingMedium

Polyfill: call( )

JS CodingEasy

Polyfill: map( )

JS CodingMedium

4. Improve a function

JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

Related hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Amazon interview
  • Apple interview
  • ByteDance interview

FAQ

What do interviewers look for in a reduce polyfill?

Correct handling of the initial value, empty-array errors when no initializer is provided, left-to-right accumulation, and not mutating the original array.

How should I explain my solution?

Walk through the accumulator lifecycle with and without an initial value, then cover sparse-array behavior if asked.

Related practice?

map polyfill, flatten array, and promise.all patterns.