JavaScript Polyfill Interview Questions: bind, Promise.all, debounce and More
12 JavaScript polyfill interview questions with working code and explanations: map, filter, reduce, bind, call, Promise.all, Promise.allSettled, debounce, throttle, flat, deep clone and curry.
Polyfill questions test whether you understand how built-in methods actually work. A polyfill is code that adds a feature to environments that lack it, and in interviews you'll be asked to write one from scratch. Below are the 12 most asked polyfills with interview-ready code and the edge cases that earn extra points.
Say the steps out loud: check the native signature, write the happy path, then handle edge cases (empty input, errors, this, sparse arrays). Finally, compare your output with the native method.
Array polyfills#
Q1. Write a polyfill for Array.prototype.map#
Answer: map calls a callback with (element, index, array) for each existing element and returns a new array of the results. It also accepts an optional thisArg.
Array.prototype.myMap = function (callback, thisArg) {
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
const result = new Array(this.length);
for (let i = 0; i < this.length; i++) {
if (i in this) { // skip holes in sparse arrays
result[i] = callback.call(thisArg, this[i], i, this);
}
}
return result;
};
[1, 2, 3].myMap((n) => n * 2); // [2, 4, 6]Use a regular function, not an arrow, so that this is the array the method was called on.
Q2. Write a polyfill for Array.prototype.filter#
Array.prototype.myFilter = function (callback, thisArg) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (i in this && callback.call(thisArg, this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};Explanation: unlike map, the result length can differ from the input, so we push only the elements whose callback returns a truthy value.
Q3. Write a polyfill for Array.prototype.reduce#
Array.prototype.myReduce = function (callback, initialValue) {
let i = 0;
let acc = initialValue;
if (arguments.length < 2) {
// no initial value: use the first existing element
while (i < this.length && !(i in this)) i++;
if (i >= this.length) {
throw new TypeError("Reduce of empty array with no initial value");
}
acc = this[i++];
}
for (; i < this.length; i++) {
if (i in this) acc = callback(acc, this[i], i, this);
}
return acc;
};Edge case interviewers check: use arguments.length, not initialValue === undefined, because undefined is a valid initial value. An empty array with no initial value must throw.
Q4. Flatten a nested array (Array.prototype.flat)#
function flat(arr, depth = 1) {
const result = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
result.push(...flat(item, depth - 1));
} else {
result.push(item);
}
}
return result;
}
flat([1, [2, [3, [4]]]]); // [1, 2, [3, [4]]]
flat([1, [2, [3, [4]]]], Infinity); // [1, 2, 3, 4]A common follow-up is an iterative version using a stack, which avoids recursion limits on very deep arrays.
Function polyfills#
Q5. Write a polyfill for Function.prototype.call and apply#
Answer: temporarily attach the function to the target object, call it as a method (so this is the object), then remove it. A Symbol key avoids overwriting an existing property.
Function.prototype.myCall = function (context, ...args) {
context = context ?? globalThis;
const key = Symbol("fn");
context[key] = this; // "this" is the function being called
const result = context[key](...args);
delete context[key];
return result;
};
Function.prototype.myApply = function (context, args = []) {
return this.myCall(context, ...args);
};
function greet(greeting) { return greeting + ", " + this.name; }
greet.myCall({ name: "Asha" }, "Hi"); // "Hi, Asha"Q6. Write a polyfill for Function.prototype.bind#
Function.prototype.myBind = function (context, ...boundArgs) {
const fn = this;
return function (...callArgs) {
return fn.apply(context, [...boundArgs, ...callArgs]);
};
};
const user = { name: "Ravi" };
function hello(city, country) {
return `${this.name} from ${city}, ${country}`;
}
const bound = hello.myBind(user, "Pune");
bound("India"); // "Ravi from Pune, India"Explanation: bind doesn't call the function; it returns a new function with this fixed and supports partial application (arguments given now plus arguments given later). A senior-level follow-up: when the bound function is called with new, native bind ignores the bound this.
Promise polyfills#
Q7. Implement Promise.all#
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
if (promises.length === 0) return resolve([]);
promises.forEach((p, index) => {
Promise.resolve(p) // also accept plain values
.then((value) => {
results[index] = value; // keep input order
completed++;
if (completed === promises.length) resolve(results);
})
.catch(reject); // fail fast on the first rejection
});
});
}Three details interviewers look for:
- Results are stored by index, not pushed, so order matches the input even if promises settle out of order.
- Count completions with a counter;
results.lengthis unreliable when a later index is filled first. - Handle the empty array, and wrap values with
Promise.resolve.
Q8. Implement Promise.allSettled and Promise.race#
function promiseAllSettled(promises) {
return promiseAll(
promises.map((p) =>
Promise.resolve(p).then(
(value) => ({ status: "fulfilled", value }),
(reason) => ({ status: "rejected", reason })
)
)
);
}
function promiseRace(promises) {
return new Promise((resolve, reject) => {
promises.forEach((p) => Promise.resolve(p).then(resolve, reject));
});
}allSettled never rejects: it converts each outcome into an object. race works because a promise can only settle once, so later calls to resolve or reject are ignored.
| Method | Resolves when | Rejects when |
|---|---|---|
Promise.all | All fulfil | Any rejects |
Promise.allSettled | All settle | Never |
Promise.race | First settles (fulfilled) | First settles (rejected) |
Promise.any | First fulfils | All reject (AggregateError) |
Utility functions#
Q9. Implement debounce#
Answer: debounce delays a function until the calls stop for delay ms. Each new call cancels the previous timer. Typical use: a search box that calls the API only after the user stops typing.
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), delay);
};
}
const onSearch = debounce((q) => fetchResults(q), 300);
input.addEventListener("input", (e) => onSearch(e.target.value));The arrow function inside setTimeout keeps the caller's this, and the closure keeps timerId private between calls.
Q10. Implement throttle#
Answer: throttle runs a function at most once every limit ms, no matter how often it is called. Typical use: scroll and resize handlers.
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}
window.addEventListener("scroll", throttle(updateProgressBar, 100));Debounce waits for a pause and runs once at the end; throttle runs regularly during continuous activity.
Q11. Write a deep clone function#
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== "object") return value;
if (value instanceof Date) return new Date(value);
if (value instanceof RegExp) return new RegExp(value);
if (seen.has(value)) return seen.get(value); // circular reference
const copy = Array.isArray(value) ? [] : {};
seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) {
copy[key] = deepClone(value[key], seen);
}
return copy;
}Explanation: primitives are returned as-is; objects and arrays are copied recursively. The WeakMap handles circular references, which would otherwise cause infinite recursion. Mention that modern browsers ship structuredClone(), and that JSON.parse(JSON.stringify(x)) loses dates, undefined, functions and fails on cycles.
Q12. Implement curry#
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return (...next) => curried.apply(this, [...args, ...next]);
};
}
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
curriedAdd(1, 2)(3); // 6fn.length is the number of declared parameters. Keep collecting arguments until there are enough, then call the original function. Variation: sum(1)(2)(3)() with an unknown number of calls, which ends when called with no arguments.
Quick revision#
| Polyfill | Key detail |
|---|---|
| map / filter | Regular function for this; skip holes with i in this |
| reduce | Check arguments.length; throw on empty array without initial value |
| call / apply | Attach the function under a Symbol key |
| bind | Return a function; support partial arguments |
| Promise.all | Store by index, count completions, reject fast |
| debounce | clearTimeout on every call |
| throttle | Compare timestamps |
| deep clone | Recursion + WeakMap for cycles |
Related reading: this, call, apply and bind, promises and async/await and array method interview questions.
Key takeaways#
- Prototype polyfills use regular functions so
thisrefers to the array or function they're called on. Promise.allmust preserve order, count completions and reject on the first failure.- Debounce waits for silence; throttle limits the rate.
- Deep clone needs recursion and a WeakMap for circular references;
structuredCloneexists natively. - Always mention edge cases: empty inputs, invalid callbacks, sparse arrays and
undefinedinitial values.