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 TypeError if callback is not a function
  • Return a new array — never mutate the original
  • Pass (element, index, array) to each callback invocation
  • Respect the optional thisArg as the callback's this
  • Preserve holes in sparse arrays (i in this check)

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

Read the full write-up for Array.prototype.map Polyfill
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it