Polyfills interviewers ask · core
Array polyfills: map, filter, reduce and flat
Array method polyfills loop over indexes and use i in this to skip holes, call the callback with (element, index, array) and the optional thisArg, and reduce must start from the first present element and throw a TypeError on an empty array with no initial value.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Use a classic for loop from 0 to the length read at the start; elements added during the loop are not visited.
- Skip holes with if (i in arr). map keeps holes in its result (same length).
- Validate the callback: typeof cb !== 'function' throws TypeError.
- map: result = new Array(len). filter: push when the callback returns truthy. forEach returns undefined.
- reduce(acc, cur, index, array): without an initial value, start from the first present element; if there is none, throw TypeError ('Reduce of empty array with no initial value'). reduceRight goes backwards.
- flat(depth = 1): recursion or a stack; skips holes; flat(Infinity).
- Follow-up: implement map and filter using your reduce (Adobe, Cloudsek).
The red pen
Common traps: mistake → fix
Mistake: Using forEach inside the polyfill
Fix: allowed, but interviewers want the explicit loop and hole handling.
Mistake: Ignoring holes and thisArg.
Mistake: Starting reduce with acc = 0 when no initial value is given
Fix: wrong for strings and objects.
Easy to hard
Questions interviewers ask, easy to hard
- Write myMap and myFilter.
- Write myReduce with and without an initial value.
- Implement map and filter using reduce.
- What does the spec do with holes and thisArg?
- Implement flat(depth) without recursion.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.