Skip to the solution
MediumDSA7 min read

Polyfill Array.prototype.reduce

598 views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myReduce from scratch — matching real native reduce's own complete, documented contract, including its behavior with and without an explicit initial value."

Examples:

Code
[1,2,3,4].reduce((acc, v) => acc + v, 0); // 10

Clarifying questions expected:

  • With no initial value provided, does the FIRST present element become the implicit seed?
  • What is the real, correct behavior for a genuinely empty array with no initial value — does it throw?
  • Does a real hole in a sparse array need to be correctly skipped, matching real native reduce's own documented behavior?

Code / implementation expected: Yes — real, direct proof matching real native reduce, WITH an explicit initial value, WITHOUT one, and on a genuinely empty array with no seed.

  • polyfill
  • array
  • reduce

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the reduce polyfill matches real native reduce both with and without an initial value, and correctly throws on an empty array with no seed

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 111 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement debounce() with leading/trailing and cancel/flush

Continue