Implementing core JavaScript methods from scratch is the most revealing exercise in frontend engineering. This guide walks through every major polyfill — Array.map, filter, reduce, Function.call/apply/bind, all four Promise combinators, Object.assign, GroupBy, DOM APIs, and JSON.stringify — with full spec-compliant implementations and 14 interactive problems.
A polyfill is code that implements a feature on environments that don't support it natively. The word comes from Polyfilla — a product used to fill cracks in walls. In JavaScript, polyfills fill the gaps between what old runtimes support and what modern specs define.
But the real reason to implement polyfills yourself goes beyond browser compatibility. It is the single most effective way to understand the JavaScript specification deeply. Implementing Array.prototype.map yourself forces you to confront questions that using the native method never surfaces:
What happens with sparse array holes?
How is thisArg applied to the callback?
Should the result array be dense or sparse?
What if the callback mutates the original array mid-iteration?
Polyfill PatternPolyfill pattern: check if method exists, if not define it on the prototype
The General Pattern
Every polyfill follows the same guard pattern: check if the native exists, and only define your version if it doesn't. This prevents clobbering future native implementations.
Convention in this guide: all implementations are prefixed with my (e.g., myMap, myBind) so they don't conflict with native methods. In real polyfill libraries, the guard above ensures natives are never overwritten.
Array PrototypeArray.prototype showing all methods; orange methods are polyfilled in this guide
Polyfill DetectionPolyfill detection: guard pattern flow and feature detection vs UA sniffing comparison
Key Insight
Polyfill questions are the #1 interview question type at companies like Meta, Google, and Airbnb. They test whether you understand the JavaScript spec — not just whether you can use the API.
1. Array.prototype.map
map transforms each element of an array via a callback and returns a new array of the same length. The original array is never mutated.
Sparse holes (e.g. [1,,3]) are skipped — not passed to callback
Result array has the same length as the source, preserving hole positions
Implementation
example.js
Array.prototype.myMap = function(callback, thisArg) {
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
const result = new Array(this.length); // preserve length for sparse arrays
for (let i = 0; i < this.length; i++) {
if (i in this) { // skip sparse holes
result[i] = callback.call(thisArg, this[i], i, this);
}
}
return result;
};
// Usage
[1, 2, 3].myMap(x => x * 2); // [2, 4, 6]
[1,,3].myMap(x => x * 2); // [2, empty, 6] — hole preserved
[1, 2].myMap(function() { return this.n; }, { n: 10 }); // [10, 10]
Note
Why i in this? The in operator checks whether the index is an own property of the array object. Sparse holes are not own properties — 1 in [1,,3] returns false. Checking this[i] !== undefined would fail if an element genuinely holds undefined.
Note
Why new Array(this.length)? Starting with the correct length creates the right-shaped result for sparse arrays. Using [] and push would produce a dense array and lose hole positions.
filter returns a new array containing only the elements for which the callback returns a truthy value. The result array length is always ≤ the original length.
Key Difference from map
Unlike map, the result of filter is always a dense array — there are no holes, even if the input is sparse. Holes are simply skipped and not included.
Implementation
example.js
Array.prototype.myFilter = function(callback, thisArg) {
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
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;
};
// Usage
[1, 2, 3, 4, 5].myFilter(x => x % 2 === 0); // [2, 4]
[1,,3,,5].myFilter(x => x > 2); // [3, 5] — holes skipped
["a", "b", "c"].myFilter(function(v) {
return v !== this.excluded;
}, { excluded: "b" }); // ["a", "c"]
Tip
The double guard i in this && short-circuits for holes — the callback is never invoked for a hole index. This matches the native spec where holes are skipped entirely, not treated as undefined.
reduce accumulates all array elements into a single value by applying a callback iteratively. It is the most general of the three iteration methods — both map and filter can be implemented with reduce.
Two Signatures
reduce has two calling conventions:
With initialValue: accumulator starts as initialValue, iteration starts at index 0
Without initialValue: first element becomes the accumulator, iteration starts at index 1
Warning
Calling reduce on an empty array without an initialValue throws a TypeError. This is a common interview question — your implementation must match this behavior.
Implementation
example.js
Array.prototype.myReduce = function(callback, initialValue) {
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// arguments.length >= 2 detects initialValue even if it is undefined
const hasInitial = arguments.length >= 2;
if (this.length === 0 && !hasInitial) {
throw new TypeError("Reduce of empty array with no initial value");
}
let acc = hasInitial ? initialValue : this[0];
const startIdx = hasInitial ? 0 : 1;
for (let i = startIdx; i < this.length; i++) {
if (i in this) {
acc = callback(acc, this[i], i, this);
}
}
return acc;
};
// With initialValue
[1, 2, 3].myReduce((acc, x) => acc + x, 0); // 6
[1, 2, 3].myReduce((acc, x) => acc + x, 100); // 106
// Without initialValue — first element is accumulator
[1, 2, 3].myReduce((acc, x) => acc + x); // 6 (1 is accumulator)
["b", "c"].myReduce((acc, x) => acc + x); // "bc"
// Edge case: throws on empty without initial
[].myReduce((acc, x) => acc + x); // TypeError ✓
Key Insight
The key implementation detail is arguments.length >= 2 rather than checking initialValue !== undefined. If a caller passes undefined as the second argument explicitly, it still counts as "has initial value" and the accumulator starts as undefined. The spec distinguishes presence from value.
Now that you've implemented map, filter, and reduce individually, let's compare all major Array polyfills side by side.
5 Major Array Methods — Comparison
Method
Returns
Length
Holes
Mutates?
Callback
.map()
new array, same length
same
preserved
never
(elem, idx, arr) → newElem
.filter()
new array, ≤ original
≤
removed
never
(elem, idx, arr) → boolean
.reduce()
single accumulated value
N/A
skipped
never
(acc, elem, idx, arr) → newAcc
.flat()
new flattened array
≤
removed
never
N/A (depth param)
.find()
first match or undefined
N/A
skipped
never
(elem, idx, arr) → boolean
Polyfill vs Ponyfill
A polyfill modifies the native prototype to add a missing method. A ponyfill exports a standalone function that you import and call directly — it never touches prototypes.
Polyfill
Ponyfill
Approach
Monkey-patches native prototype
Exports a plain function
Usage
arr.map(fn) — transparent
map(arr, fn) — explicit import
Global side effects
Yes — modifies Array.prototype
None — no prototype mutation
Multiple versions
Only one — last import wins
Each module imports its own version
Example library
core-js, polyfill.io
lodash, array.prototype.map npm pkg
Tip
Prefer polyfills for user-facing apps where you control the runtime (you want arr.map(fn) to always work). Prefer ponyfills for libraries and packages — never mutate prototypes in a library; consumers may have different runtime requirements.
5. Function.call & apply
Function.prototype.call and Function.prototype.apply allow you to invoke a function with an explicit this context. They are the foundation of function borrowing — reusing a method from one object on another.
Function BorrowingFunction.prototype.call, apply, bind — three ways to control this binding
apply(thisArg, [arg1, arg2, ...]) — arguments passed as an array
Both invoke the function immediately and return the result. The mnemonic: call = comma-separated, apply = array.
Implementation
The trick: temporarily set the function as a property on the context object, call it, then delete the property. This causes this inside the function to be the context object.
Why Symbol("fn")? Using a string key like "__fn__" risks colliding with a property that already exists on the context object. A Symbol is always unique — it can never clash with any existing or future property key.
bind(thisArg, ...boundArgs) returns a new function with a permanently bound this and optional pre-filled arguments. Unlike call and apply, the bound function is not invoked immediately — you call it later.
Partial Application
bind is also how you implement partial application in JavaScript: supply some arguments at bind time and the rest at call time.
example.js
function add(a, b) { return a + b; }
const add5 = add.myBind(null, 5); // bound args: [5]
add5(3); // 8 — callArgs: [3] → add(5, 3)
add5(10); // 15
The native bind also handles the case where the bound function is used as a constructor with new — in that case, the bound this is ignored and a fresh object is created. This simplified implementation doesn't handle that edge case. Mention this in interviews — it shows you know the spec beyond the happy path.
The four Promise combinators cover different strategies for composing concurrent asynchronous operations. Understanding when each one settles — and when it short-circuits — is critical.
Settles (resolve or reject) with whichever promise settles first.
example.js
Promise.myRace = function(promises) {
return new Promise((resolve, reject) => {
for (const p of promises) {
Promise.resolve(p).then(resolve, reject);
}
});
};
Promise.any — first fulfillment wins
Resolves with the first fulfilled value. Only rejects if all promises reject, yielding an AggregateError.
example.js
Promise.myAny = function(promises) {
return new Promise((resolve, reject) => {
const errors = [];
let remaining = promises.length;
if (remaining === 0) {
return reject(new AggregateError([], "All promises were rejected"));
}
promises.forEach((p, i) => {
Promise.resolve(p).then(
resolve, // first success short-circuits
(err) => {
errors[i] = err;
if (--remaining === 0) {
reject(new AggregateError(errors, "All promises were rejected"));
}
}
);
});
});
};
Promise.allSettled — wait for all, never rejects
Waits for all promises to settle. Always resolves with an array of result objects — never rejects. Each object has a status field and either value (for fulfilled) or reason (for rejected).
The order of results in Promise.all and Promise.allSettled always matches the input order, not the settlement order. This is why the implementation uses indexed assignment (results[i] = val) rather than push.
Object.assign(target, ...sources) performs a shallow merge: it copies own enumerable properties from each source to the target and returns the target.
Implementation
example.js
Object.myAssign = function(target, ...sources) {
if (target == null) {
throw new TypeError("Cannot convert undefined or null to object");
}
const to = Object(target);
for (const source of sources) {
if (source != null) {
for (const key of Object.keys(source)) {
to[key] = source[key];
}
}
}
return to;
};
// Usage
const target = { a: 1 };
Object.myAssign(target, { b: 2 }, { c: 3 });
// target is now { a: 1, b: 2, c: 3 }
// Shallow: nested objects are copied by reference
const src = { user: { name: "Alice" } };
const result = Object.myAssign({}, src);
result.user === src.user; // true — same reference!
Shallow vs Deep Merge
Object.assign only copies one level deep. For nested objects, it copies the reference — mutations to the nested object in one place affect both the source and target. A deep merge recursively merges nested objects instead of copying the reference.
Object.groupBy (ES2024) groups the elements of an iterable into an object by a key returned from a callback. It landed as a static method on Object (and Map.groupBy for a Map variant) after years as a stage 3 proposal.
Object.create(null) creates an object with no prototype — meaning there's no toString, hasOwnProperty, or other inherited keys that could accidentally conflict with group names. The native spec also uses a null-prototype object for the result.
Real-World Uses
Grouping is one of the most common data-manipulation operations: group orders by status, users by role, events by date, transactions by currency. BeforeObject.groupBy, this was typically done with reduce:
DOM polyfills require traversing the browser's document tree. The canonical example is getElementsByClassName — the method that predates querySelector in older browsers. Implementing it teaches recursive tree traversal and DOM API internals.
getElementsByClassName
The method must recursively walk every node in the DOM subtree and collect elements whose class list contains the target class name.
example.js
function getElementsByClassName(root, className) {
const results = [];
function traverse(node) {
if (node.nodeType === Node.ELEMENT_NODE) {
if (node.classList.contains(className)) {
results.push(node);
}
}
for (const child of node.childNodes) {
traverse(child);
}
}
traverse(root);
return results;
}
// Attach as polyfill if native doesn't exist
if (!document.getElementsByClassName) {
Document.prototype.getElementsByClassName = function(cls) {
return getElementsByClassName(this, cls);
};
Element.prototype.getElementsByClassName = function(cls) {
return getElementsByClassName(this, cls);
};
}
// Usage
const buttons = getElementsByClassName(document.body, "btn");
Note
The real native getElementsByClassName returns a liveHTMLCollection — it updates automatically when the DOM changes. Our polyfill returns a static array. In practice, for a polyfill, a static snapshot is usually acceptable.
DOM Tree Traversal Fundamentals
All DOM querying polyfills share the same DFS tree traversal skeleton. The key nodes to understand:
node.childNodes — all child nodes (includes text nodes, comment nodes, etc.)
node.children — only element children (no text nodes)
node.nodeType === 1 — checks if a node is an Element (same as Node.ELEMENT_NODE)
node.classList.contains(cls) — checks class membership
JSON.stringify is the most complex polyfill in this guide. It must serialize any JavaScript value to its JSON string representation following the full specification — including type coercion rules, circular reference detection, and support for the optional replacer and space parameters.
Spec Type Rules
Strings: escape special chars (\n, \", etc.), wrap in double quotes
Numbers:Infinity and NaN → null
Booleans and null: serialized as-is
undefined, functions, Symbols: skipped in objects; become null in arrays
Arrays:[item1,item2,...]
Objects:{"key":value,... — only own enumerable properties
Circular references: throw TypeError
toJSON: if an object has a toJSON() method, call it first and serialize the result
Implementation
example.js
function myJSONStringify(value, replacer, space, seen = new Set()) {
// replacer support (simplified — function form only)
if (typeof replacer === "function") {
value = replacer("", value);
}
// toJSON support
if (value !== null && typeof value === "object" && typeof value.toJSON === "function") {
value = value.toJSON();
}
// Primitives
if (value === null) return "null";
if (value === true) return "true";
if (value === false) return "false";
if (typeof value === "number") {
return (isFinite(value)) ? String(value) : "null"; // Infinity, NaN → null
}
if (typeof value === "string") {
// Escape special characters
return '"' + value
.replace(/\/g, "\\")
.replace(/"/g, '\"')
.replace(/
/g, "\n")
.replace(/
/g, "\r")
.replace(/ /g, "\t")
.replace(/[ -]/g, c => "\u" + c.charCodeAt(0).toString(16).padStart(4, "0"))
+ '"';
}
// undefined, functions, Symbols — not serializable at top level
if (
typeof value === "undefined" ||
typeof value === "function" ||
typeof value === "symbol"
) {
return undefined; // native returns undefined (not a string)
}
// Circular reference detection
if (seen.has(value)) {
throw new TypeError("Converting circular structure to JSON");
}
seen.add(value);
const indent = typeof space === "number" ? " ".repeat(space) : (space ?? "");
// Arrays
if (Array.isArray(value)) {
const items = value.map(item => {
const s = myJSONStringify(item, replacer, space, seen);
return s === undefined ? "null" : s; // undefined in arrays → null
});
seen.delete(value);
return "[" + items.join(",") + "]";
}
// Objects
const pairs = [];
for (const key of Object.keys(value)) {
const val = myJSONStringify(value[key], replacer, space, seen);
if (val !== undefined) { // skip undefined/function/symbol values
pairs.push(myJSONStringify(key) + ":" + val);
}
}
seen.delete(value);
return "{" + pairs.join(",") + "}";
}
// Usage
myJSONStringify({ a: 1, b: [2, 3], c: null }); // '{"a":1,"b":[2,3],"c":null}'
myJSONStringify({ a: undefined, b: () => {} }); // '{}'
myJSONStringify([1, undefined, 3]); // '[1,null,3]'
myJSONStringify(NaN); // 'null'
myJSONStringify(Infinity); // 'null'
Warning
The real JSON.stringify is significantly more complex — it handles BigInt (throws), Date objects via toJSON, array-form replacers (allowlist of keys), and numeric space. The implementation above covers the core cases tested in interviews.
Beyond the classic polyfills, modern JavaScript (ES2020+) introduces several APIs that are worth knowing how to implement. These are increasingly common interview topics.
Object.hasOwn
Object.hasOwn(obj, key) (ES2022) is a safer alternative toObject.prototype.hasOwnProperty.call(obj, key). It works on objects created with Object.create(null) (which lack the prototype methods).
arr.at(-1) returns the last element. The method accepts negative indices that count from the end of the array, eliminating the awkward arr[arr.length - 1] pattern.
example.js
if (!Array.prototype.at) {
Array.prototype.at = function(index) {
// Convert index to integer, handle negative
const n = Math.trunc(index) || 0;
const k = n >= 0 ? n : this.length + n;
return k >= 0 && k < this.length ? this[k] : undefined;
};
}
// Usage
const arr = [10, 20, 30, 40];
arr.at(-1); // 40 — last element
arr.at(-2); // 30
arr.at(0); // 10
arr.at(99); // undefined — out of bounds
Object.fromEntries
Object.fromEntries(iterable) is the inverse of Object.entries(). It transforms a list of key-value pairs into an object.
queueMicrotask(callback) schedules a microtask — it runs after the current task completes but before the browser renders. It's equivalent to Promise.resolve().then(callback).
The microtask queue is drained after every macrotask — before rendering, before event handlers, before timeouts. This is why Promise.resolve().then()runs before setTimeout(fn, 0).
Microtask queue is drained before each macrotask. This means a microtask that queues another microtask (queueMicrotask(() => queueMicrotask(fn))) will delay the next macrotask indefinitely — a pattern known as microtask starvation. Don't do this.
Interview Cheat Sheet
Polyfill questions appear at nearly every senior frontend interview. Here are the 10 most common follow-up questions with concise answers.
1Why use `i in this` instead of `this[i] !== undefined` in map/filter?
The `in` operator checks whether the index is an own property of the array. Sparse holes are NOT own properties — `1 in [1,,3]` returns false. Checking `!== undefined` would fail if an element genuinely stores the value undefined, treating it incorrectly as a hole.
2How does `call` work internally? Walk me through the implementation.
The trick is to temporarily set the function as a property on the context object using a Symbol key. When invoked as a method of that object, `this` inside the function resolves to the object. After the call, delete the Symbol property to clean up. Symbol prevents key collisions with existing properties.
3What does `bind` return and when is it invoked?
bind returns a new function (not a call result). The returned function, when called later, invokes the original with the pre-bound `this` and pre-filled args merged with the call-time args. Unlike call/apply which invoke immediately, bind defers invocation.
4What's the difference between Promise.all and Promise.allSettled?
Promise.all short-circuits on the first rejection — it rejects immediately and ignores all other promises. Promise.allSettled NEVER rejects — it waits for every promise to settle and returns an array of {status, value/reason} objects for each one, regardless of outcome.
5Why does reduce throw on an empty array with no initialValue?
Without an initialValue, reduce uses the first element as the accumulator and starts iterating at index 1. An empty array has no first element — there is nothing to use as the initial accumulator. The spec mandates a TypeError in this case. The check is arguments.length >= 2 (not checking if initialValue is undefined, since undefined is a valid initial value).
6How do you detect sparse array holes vs elements that hold undefined?
Use `i in arr`. The `in` operator returns false for hole indices because holes are not own properties of the array object. arr[i] === undefined returns true for both holes AND elements explicitly set to undefined — making it unreliable for sparse array handling.
7What's the difference between Object.assign and a deep merge?
Object.assign copies own enumerable properties one level deep — nested objects are copied by reference, not by value. A deep merge recursively merges nested objects: both source and target sub-objects are merged so keys from the target that aren't in the source are preserved, rather than being replaced by the source object wholesale.
8How does Object.groupBy differ from a reduce-based grouping?
Functionally equivalent — both group elements by a key. Object.groupBy (ES2024) is cleaner to call, works on any iterable (not just arrays), and returns a null-prototype object to avoid prototype key collisions. The reduce approach requires more boilerplate but has been available for much longer and doesn't need a polyfill.
9What happens to undefined, functions, and Symbols in JSON.stringify?
In an object: the key-value pair is omitted entirely (not serialized). In an array: the value becomes null (to preserve array length and index positions). At the top level: JSON.stringify returns undefined (not a string — the function returns undefined, not the string 'undefined').
10Why use Symbol() for the temporary key in the call implementation?
A Symbol is guaranteed to be unique — it cannot equal any other property key, string or symbol. Using a fixed string like '__fn__' risks colliding with an existing property on the context object, causing it to be overwritten during the call. Symbols bypass both string-key collisions and enumeration in for...in loops.
Key Takeaways
1.Always guard polyfills with `if (!Method.prototype.myMethod)` to avoid overwriting future native implementations. In this guide we use the `my` prefix to coexist with natives.
2.Sparse array holes are not own properties — use `i in arr` (not `arr[i] !== undefined`) in map, filter, and reduce to correctly skip holes rather than processing them as undefined.
3.The arguments.length check in reduce is critical: `arguments.length >= 2` correctly detects when initialValue was passed even if its value is `undefined`, which is a valid accumulator.
4.The call/apply implementation trick — temporarily set the function as a Symbol-keyed property on the context object — makes `this` resolve correctly without any native binding API.
5.bind returns a new function, not a result. The bound function closes over the original `this` and pre-filled args, supporting partial application naturally.
6.Promise.all and Promise.any short-circuit on failure/success respectively. Promise.race short-circuits on either. Only Promise.allSettled waits for all and never rejects — the safest combinator for parallel operations where all outcomes matter.
7.Object.assign is shallow: nested objects are copied by reference. A deep merge requires recursion and must preserve keys from the target that are absent in the source.
8.JSON.stringify has strict type rules: Infinity and NaN become null, undefined/function/Symbol values are omitted from objects and become null in arrays. Circular references throw TypeError.
9.DOM polyfills require recursive DFS tree traversal. `node.nodeType === 1` filters element nodes from text and comment nodes. The `classList.contains()` API is the correct way to check class membership.
10.Every polyfill you implement is a direct window into the JavaScript specification. The edge cases — sparse holes, argument presence detection, circular references — are precisely what interviewers test, and they reveal whether you understand the language or just its surface API.