Skip to the solution
EasyDSAAsked in 20246 min read

Array.prototype.forEach Polyfill

1.1k views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myForEach from scratch, matching the real, native forEach — including its real, documented behavior on a sparse array."

Examples:

Code
[10, 20, 30].myForEach((v, i, arr) => console.log(v, i, arr.length));

Clarifying questions expected:

  • Does the callback need to receive the index and the whole original array, matching the real native signature?
  • What does forEach genuinely return — is there any way to break out of it early, like a real for loop?
  • Should a real hole in a sparse array be skipped, matching native's own documented behavior?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native forEach, confirming identical call counts on a sparse array and an identical return value.

  • polyfill
  • array

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

6 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 forEach polyfill matches the real native method exactly, including hole-skipping on a sparse array and its always-undefined return value

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 20 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 nextEasy

Implement _.range(start, end, step) generator

Continue