Array.prototype.map Polyfill
ArraysPolyfill
Implement Array.prototype.myMap that behaves identically to the native map.
Function Signature:
Array.prototype.myMap = function (callback, thisArg) { }
Requirements:
- Throw
TypeErrorifcallbackis not a function - Return a new array — never mutate the original
- Pass
(element, index, array)to each callback invocation - Respect the optional
thisArgas the callback'sthis - Preserve holes in sparse arrays (
i in thischeck)
Examples
Example 1
Input
[1, 2, 3].myMap(x => x * 2)Output
[2, 4, 6]Explanation
Each element is doubled and collected into a new array.
Example 2
Input
['a', 'b', 'c'].myMap((el, i) => el + i)Output
['a0', 'b1', 'c2']Explanation
The callback receives the index as its second argument.
Constraints
- Do not use the native Array.prototype.map internally
- The original array must not be mutated
Notes
- Use `i in this` (not `this[i] !== undefined`) to detect holes in sparse arrays
- `arguments.length` is not needed here — thisArg defaults to undefined naturally
Hints
Editorial: Array.prototype.map Polyfill
Implementing Array.prototype.map from scratch
map returns a new array where every element is the result of calling the callback. It never mutates the original.
What the interviewer checks
- Do you pass all three arguments
(element, index, array)to the callback? - Do you return a new array?
- Do you support the optional
thisArg? - Do you preserve holes in sparse arrays?
Implementation
Array.prototype.myMap = function (callback, thisArg) { if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } const result = []; for (let i = 0; i < this.length; i++) { // skip holes so sparse arrays stay sparse if (i in this) { result[i] = callback.call(thisArg, this[i], i, this); } } return result; };
Key details
i in this— checks for the property on the array object, not just whether the value isundefined. This correctly skips holes in sparse arrays like[1, , 3]where index 1 doesn't exist. Most candidates writethis[i] !== undefinedwhich is wrong.result[i] = ...— write by index, not push, to preserve sparse structure in the output.callback.call(thisArg, ...)—thisArgdefaults toundefinednaturally when not passed, matching the spec.
Edge cases to mention
- The callback receives three arguments, not one — forgetting
indexandarrayis a common miss. thisArgis how methods on other objects can be used as the callback with the rightthis.- Sparse arrays:
[1,,3].myMap(x => x * 2)should produce[2,,6], not[2, undefined, 6].
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it