FrontendInterviews.dev

Loading problem…

71. Array.prototype.map (Polyfill)

Easy•
Acceptance: 76.19%
•
🔓3/3 Pro unlocks today

Implement Array.prototype.myMap — a polyfill that behaves like native Array.prototype.map.

Mapping is a foundational skill in JavaScript interviews, but many implementations miss important details: sparse arrays (holes), callback arguments, thisArg binding, and mutation behavior during iteration.

Requirements

1) Core behavior

  • arr.myMap(callbackFn, thisArg?) returns a new array.
  • It calls callbackFn once per existing element in the array (skip holes).
  • It passes (value, index, array) to the callback.
  • It does not mutate the original array (unless the callback does).

2) Edge cases / correctness

  • Preserve output array length equal to the input length.
  • Skip missing indices in sparse arrays (holes remain holes in output).
  • thisArg binds the callback this (non-arrow callbacks).
  • Throw TypeError if callbackFn is not a function.
  • Use the array length as captured at start (items appended beyond initial length are not visited).

Constraints

  • Must not use Array.prototype.map internally
  • callbackFn must be a function; otherwise throw TypeError
  • Callback receives (value, index, array)
  • Must skip holes (sparse array missing indices) and preserve holes in output
  • Output array length must equal input length
  • Must support optional thisArg for callback this-binding
  • Should behave correctly when array is mutated during iteration (length captured at start)