QuestionsJavaScript

Polyfill Array map / filter / reduce

PolyfillsMediumJavaScript

Reimplement Array.prototype.map, filter, and reduce from scratch. What edge cases must a faithful polyfill handle?

What it tests

Knowing the exact callback contract (value, index, array), the this-arg, sparse-array skipping, and reduce's no-initial-value rule.

Approach & answer

These are the bread-and-butter polyfill challenges — the interviewer is checking you know the SIGNATURE and edge cases, not just the happy path. The callback everywhere is `(element, index, array)`, and map/filter accept an optional `thisArg` bound via callback.call(thisArg, ...). map returns a NEW array of the same length with each element transformed; filter returns a new array containing only elements for which the callback is truthy. Sparse arrays: native map/filter/reduce SKIP holes (indices never assigned) — a faithful polyfill guards each index with `Object.hasOwn(this, i)` (or `i in this`) so holes stay holes rather than becoming undefined. reduce is the subtle one: with an initialValue, the accumulator starts there and iteration begins at index 0; WITHOUT an initialValue, the accumulator is the first present element and iteration starts at the next — and calling reduce on an empty array with no initial value must THROW a TypeError ('Reduce of empty array with no initial value'). All three should validate the callback is a function (throw TypeError otherwise) and read length once up front. Getting reduce's two-mode initialisation and the empty-array throw right is what separates a real answer from a toy one.

Use this technique when

Interview polyfill rounds, understanding what native iteration methods actually guarantee, and reasoning about sparse arrays and reduce's initial-value semantics.

Complexity

O(n) time, O(n) space for map/filter, O(1) extra for reduce.

References

js