A polyfill is code that adds a standard feature to an environment that doesn't have it yet, such as Promise.any or Array.prototype.flat in an older browser. It's written in plain JavaScript that the old environment can already run, and it follows the specification, the document that defines how the feature behaves, as closely as it can. Code written for new browsers then works in old ones too. The name comes from Polyfilla, a paste for filling cracks in walls: a polyfill fills the gaps in a browser.
A real polyfill checks for the feature first, as in if (!Promise.any), and defines it only when it's missing, so a browser that has the built-in keeps its own version:
if (!Array.prototype.flat) {
Array.prototype.flat = function flat(depth) {
// the steps the specification lists, written in plain JavaScript
};
}
Every array gets its methods from one shared object, Array.prototype, and every function from Function.prototype. So a method added there appears on every array or function in the program, even ones created before it was added, and inside it this is the array or function it was called on. Careful polyfills add it with Object.defineProperty rather than = as above, so that, like the built-ins, it isn't enumerable and doesn't show up in a for...in loop.
When an interviewer asks you to write a polyfill, they mean: reproduce a built-in's behaviour yourself, without calling it. It shows you know exactly what the built-in does, beyond its everyday use. The details are the point, because code written against the standard relies on them too:
| Built-in | Everyday use | Details a polyfill must match too |
|---|---|---|
Array.prototype.map | [1, 2].map((n) => n * 2) is [2, 4] | thisArg, holes, and the TypeError for a callback that isn't a function, thrown even when the array is empty |
Function.prototype.bind | A function with a fixed this | Preset arguments, and calling the result with new |
Promise.all | Waits for several promises | Plain values among them, an empty input, and an argument that isn't iterable |
Object.create | An object that inherits from the one you pass | null as the prototype, and a TypeError for one that's neither an object nor null |
JSON.stringify | Turns data into text | undefined and functions, toJSON, and a TypeError on cycles |
These tasks give your version its own name, such as Array.prototype.myMap, Object.myCreate, or JSON.myStringify, or make it a stand-alone function, such as promiseAll(iterable) or objectIs(a, b). Replacing the real method would change it for every other piece of code on the page, and leave you no built-in to compare yours with.
In production you rarely write polyfills by hand: libraries such as core-js provide them, and Babel can add the ones your target browsers need. A polyfill can only add missing objects, functions, and methods. New syntax, such as ?. or class, can't be added that way: a compiler has to rewrite it as older syntax, which is called transpiling.
An array's length counts slots, and a slot can be empty: no element at all, not even undefined. That empty slot is called a hole, and an array with holes is called sparse. Reading a hole gives undefined, the value you get for any property that doesn't exist, so it looks like an element holding undefined. Object.keys, which lists the indexes an array really has, tells the two apart:
const withHole = [1, , 3]; // nothing between the commas
const withUndefined = [1, undefined, 3];
withHole.length; // 3
withUndefined.length; // 3
withHole[1]; // undefined
withUndefined[1]; // undefined
Object.keys(withHole); // ["0", "2"]: there's no element at index 1
Object.keys(withUndefined); // ["0", "1", "2"]: there is one, and its value is undefined
Holes appear in a few ways:
| How | Example | Result |
|---|---|---|
| A gap in an array literal | [1, , 3] | A hole at index 1 |
new Array with one number | new Array(3) | Three holes, and length is 3 |
delete on an element | delete arr[1] | Index 1 becomes a hole, and length doesn't change |
| Writing past the end | arr[5] = 6 on [1, 2, 3] | Holes at indexes 3 and 4, and length is 6 |
Making length bigger | arr.length = 5 on [1, 2, 3] | Holes at indexes 3 and 4 |
Consoles mark holes so you can spot them: Chrome shows [1, , 3] as [1, empty, 3], and Node as [ 1, <1 empty item>, 3 ].
Built-in methods don't agree on what to do with a hole: some skip it, some keep it in their result, and some read it as undefined, or write null in JSON. That's why every task that rebuilds one of them says exactly what to do with holes. Here's [1, , 3] going through a few:
| Call | Result | What happened to the hole |
|---|---|---|
[1, , 3].filter(() => true) | [1, 3] | Skipped: the callback isn't called for it, and the result has no hole |
[1, , 3].map((n) => n * 10) | [10, , 30] | Skipped, but kept: the result has a hole in the same place |
[1, , 3].reduce((sum, n) => sum + n) | 4 | Skipped: 1 starts the total, and the callback runs once, to add 3 |
[1, , 3].flat() | [1, 3] | Dropped |
Array.from([1, , 3]) | [1, undefined, 3] | Read as undefined, which becomes a real element |
JSON.stringify([1, , 3]) | "[1,null,3]" | Written as null |
== and === aren't the only ways JavaScript compares values. The specification, the document that defines the language, names two more, SameValue and SameValueZero, and each built-in uses the one that suits it. Like ===, both compare without converting types, so "1" never equals 1, and two objects are equal only when they're the same object. ===, SameValue, and SameValueZero differ only on two unusual numbers: NaN and -0.
NaN, short for not a number, is what you get from math that has no numeric answer, such as 0 / 0 or Number("abc"). The floating-point standard that JavaScript numbers follow says NaN equals nothing, itself included, so NaN === NaN is false. -0 is a negative zero, which you get from, for example, -1 * 0 or Math.round(-0.4). -0 === 0 is true and String(-0) is "0", but it isn't quite the same number: 1 / -0 is -Infinity, while 1 / 0 is Infinity.
| Values | == | === | SameValueZero | SameValue |
|---|---|---|---|---|
NaN and NaN | false | false | true | true |
0 and -0 | true | true | true | false |
"1" and 1 | true | false | false | false |
null and undefined | true | false | false | false |
| Two objects with the same contents | false | false | false | false |
So SameValueZero is === with one change: NaN equals NaN. SameValue makes the same change and one more: it tells 0 and -0 apart, which makes it the strictest of the three. You can call SameValue yourself, as Object.is(a, b). SameValueZero has no function of its own; you meet it inside the built-ins that use it:
| Comparison | Used by |
|---|---|
=== | === and !==, indexOf and lastIndexOf on arrays, and the cases of a switch |
| SameValueZero | includes on arrays, the keys of a Map and the values of a Set, which store -0 as 0, and Map.groupBy, which groups keys as a Map does |
| SameValue | Object.is, React when it compares state and hook dependencies, and toBe in Jest and Vitest |
[NaN].indexOf(NaN); // -1: indexOf uses ===, so it never finds NaN
[NaN].includes(NaN); // true: includes uses SameValueZero
[-0].includes(0); // true
Object.is(NaN, NaN); // true
Object.is(0, -0); // false
const set = new Set([NaN, NaN, 0, -0]);
set.size; // 2: one NaN and one zero
new Map([[-0, "zero"]]).get(0); // "zero": the key -0 was stored as 0
Why make NaN equal itself? For arithmetic, NaN === NaN being false makes sense: two failed calculations needn't be the same failure. For finding things, it's a trap: an array can hold NaN and indexOf still won't find it, and a Map that compared keys with === could store a NaN key but never read it back. So Map and Set (ES2015) and includes (ES2016) were given SameValueZero. It keeps 0 and -0 together, as === does, since nearly all code treats them as the same number.
Write Array.prototype.myIncludes(searchElement, fromIndex), which works like the built-in includes without calling it. It returns true if an element of the array equals searchElement, and false if none does.
Elements are compared the way the spec's SameValueZero does: like ===, with no type conversion, except that NaN equals NaN. 0 and -0 are equal, as they are with ===. That's why [NaN].includes(NaN) is true, while [NaN].indexOf(NaN) is -1.
Every index is checked, holes included, and a hole reads as undefined. So [1, , 3].myIncludes(undefined) is true.
fromIndex is a whole number: the index where the search starts. It defaults to 0. A negative fromIndex counts back from the end, so -1 means the last index; if that's still below 0, the search starts at 0. A fromIndex at or past the length searches nothing and gives false.
[1, 2, 3].myIncludes(2); // true
["1", 2].myIncludes(1); // false: no type conversion
[NaN].myIncludes(NaN); // true
[-0].myIncludes(0); // true
[1, , 3].myIncludes(undefined); // true: the hole reads as undefined
[1, 2, 3].myIncludes(1, 1); // false: starts at index 1
[1, 2, 3].myIncludes(3, -1); // true: starts at index 2
[1, 2, 3].myIncludes(1, -10); // true: -10 + 3 is below 0, so it starts at 0
expect([1, 2, 3].myIncludes(2)).toBe(true);
expect(["a", "b"].myIncludes("b")).toBe(true);
expect([1, 2, 3].myIncludes(4)).toBe(false);
expect([].myIncludes(undefined)).toBe(false);
expect(["1", 2].myIncludes(1)).toBe(false);
expect([0, ""].myIncludes(false)).toBe(false);
expect([null].myIncludes(undefined)).toBe(false);
expect([true].myIncludes(1)).toBe(false);
const item = { id: 1 };
expect([{ id: 0 }, item].myIncludes(item)).toBe(true);
expect([{ id: 1 }].myIncludes({ id: 1 })).toBe(false);
expect([1, NaN].myIncludes(NaN)).toBe(true);
expect([1, 2].myIncludes(NaN)).toBe(false);
expect(["NaN", "text", undefined].myIncludes(NaN)).toBe(false);
expect([-0].myIncludes(0)).toBe(true);
expect([1, 0].myIncludes(-0)).toBe(true);
expect([1, , 3].myIncludes(undefined)).toBe(true);
expect(new Array(3).myIncludes(undefined)).toBe(true);
expect([1, , 3].myIncludes(null)).toBe(false);
expect([1, 2, 3].myIncludes(1, 1)).toBe(false);
expect([1, 2, 3].myIncludes(2, 1)).toBe(true);
expect([1, 2, 3].myIncludes(1, 0)).toBe(true);
expect([1, 2, 3].myIncludes(3, 3)).toBe(false);
expect([1, 2, 3].myIncludes(3, 10)).toBe(false);
expect([1, 2, 3].myIncludes(3, -1)).toBe(true);
expect([1, 2, 3].myIncludes(2, -1)).toBe(false);
expect([1, 2, 3].myIncludes(1, -3)).toBe(true);
expect([1, 2, 3].myIncludes(1, -10)).toBe(true);
// Starts at index 0: there's no index -7 to read.
expect([1, 2, 3].myIncludes(undefined, -10)).toBe(false);
const builtIn = Array.prototype.includes;
Array.prototype.includes = function () {
throw new Error("myIncludes called the built-in includes");
};
let results;
try {
results = [[1, NaN].myIncludes(NaN), [1, 2].myIncludes(3)];
} finally {
Array.prototype.includes = builtIn;
}
expect(results).toEqual([true, false]);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Array.prototype.includes. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.