Skip to the solution
EasyDSA7 min read

Polyfill Array.prototype.map from scratch

1.2k views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myMap from scratch, matching the real, native Array.prototype.map — including its thisArg support and its real behavior on a sparse array."

Examples:

Code
[1,2,3].myMap(n => n * 2); // [2, 4, 6]

Clarifying questions expected:

  • Does the callback need to receive the current index and the whole original array, matching the real native signature?
  • Should a real, optional thisArg second parameter be supported, matching Array.prototype.map's own real contract?
  • What is real, native map's own documented behavior for a "hole" in a sparse array — does the callback even run for it?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native Array.prototype.map, across 4 real cases including the subtle sparse-array hole-skipping behavior.

  • polyfill
  • array
  • map

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 map() polyfill matches the real native Array.prototype.map exactly, including correctly skipping a genuine hole in a sparse array

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 17 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

Custom Array.prototype.flatmap polyfill

Continue