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.
Unicode gives every character a number, called its code point, written like U+0041 for A or U+1F600 for π. JavaScript strings store text in UTF-16, an encoding that writes each code point as one or two 16-bit numbers, called code units. Code points up to U+FFFF, which include the letters of most writing systems, take one unit. Those above it, such as most emoji and the musical symbol π (U+1D11E), take two, called a surrogate pair.
| Character | Code point | Code units | length |
|---|---|---|---|
A | U+0041 | 0x0041 | 1 |
β¬ | U+20AC | 0x20AC | 1 |
π | U+1D11E | 0xD834, 0xDD1E | 2 |
π | U+1F600 | 0xD83D, 0xDE00 | 2 |
length, indexes like str[1], slice, charCodeAt, and split("") all count code units. Iterating a string, with for...of or spread, goes one code point at a time, so a pair stays together:
const word = "aπb";
word.length; // 4: one unit for a, two for π, one for b
word[1]; // "\uD834": half of the pair, not a character
word.split(""); // ["a", "\uD834", "\uDD1E", "b"]
[...word]; // ["a", "π", "b"]
for (const char of word) console.log(char); // a, then π, then b
word.codePointAt(1).toString(16); // "1d11e": the whole code point
It matters whenever you count or cut text. A character limit checked with length counts π as 2, slice can cut a pair in half, and split("").reverse() swaps the two halves of a pair, which breaks the character. Even a code point isn't always what a reader sees as one character: ππ½ is two, a thumbs up and a skin tone. Intl.Segmenter splits text into the characters a reader sees.
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 |
Write Array.myFrom(items, mapFn, thisArg), which works like Array.from without calling it. It always returns a new plain array.
If items is iterable (it has a Symbol.iterator method, as arrays, strings, Sets, Maps, and generators do), the result holds the values its iterator produces, in order, even when items also has a length. Strings are iterated by code point, so a character made of two UTF-16 code units, like "π", stays one element, and an array's holes come out as undefined.
Otherwise items is an array-like: the result has length elements, read from indexes 0 to length - 1, with undefined wherever an index is missing. A missing length means 0.
If mapFn is given, each element is replaced by mapFn(value, index), called with exactly those two arguments and with thisArg as its this. Throw a TypeError if items is null or undefined, or if mapFn is given (not undefined) but isn't a function.
Array.myFrom(new Set([1, 2, 2, 3])); // [1, 2, 3]
Array.myFrom("aπ"); // ["a", "π"]
Array.myFrom({ length: 3, 0: "x", 2: "z" }); // ["x", undefined, "z"]
Array.myFrom({ length: 3 }, (_, i) => i * 2); // [0, 2, 4]
expect(Array.myFrom(new Set([1, 2, 2, 3]))).toEqual([1, 2, 3]);
expect(Array.myFrom(new Map([["a", 1]]))).toEqual([["a", 1]]);
expect(Array.myFrom("aπb")).toEqual(["a", "π", "b"]);
function* letters() {
yield "a";
yield "b";
}
expect(Array.myFrom(letters())).toEqual(["a", "b"]);
const both = {
length: 5,
*[Symbol.iterator]() {
yield 1;
},
};
expect(Array.myFrom(both)).toEqual([1]);
const sparse = [1, , 3];
const copy = Array.myFrom(sparse);
expect(copy).not.toBe(sparse);
expect(copy).toEqual([1, undefined, 3]);
expect(1 in copy).toBe(true);
const result = Array.myFrom({ length: 3, 0: "x", 2: "z" });
expect(result).toEqual(["x", undefined, "z"]);
expect(1 in result).toBe(true);
expect(Array.myFrom({ 0: "ignored" })).toEqual([]);
const mapFn = spy(function (value, index) {
return this.prefix + value + index;
});
expect(Array.myFrom(["a", "b"], mapFn, { prefix: "#" })).toEqual(["#a0", "#b1"]);
expect(mapFn.calls[0].args).toEqual(["a", 0]);
expect(Array.myFrom({ length: 3 }, (_, index) => index * 2)).toEqual([0, 2, 4]);
expect(() => Array.myFrom(null)).toThrow(TypeError);
expect(() => Array.myFrom(undefined)).toThrow(TypeError);
expect(() => Array.myFrom([1], 42)).toThrow(TypeError);
expect(() => Array.myFrom([], "double")).toThrow(TypeError);
expect(() => Array.myFrom([], null)).toThrow(TypeError);
expect(Array.myFrom([1], undefined)).toEqual([1]);
const builtIn = Array.from;
Array.from = function () {
throw new Error("myFrom called the built-in Array.from");
};
let fromString;
let fromArrayLike;
try {
// A string, not a Set or a Map: console.log shows those with Array.from.
fromString = Array.myFrom("ab");
fromArrayLike = Array.myFrom({ length: 1, 0: "c" });
} finally {
Array.from = builtIn;
}
expect(fromString).toEqual(["a", "b"]);
expect(fromArrayLike).toEqual(["c"]);
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.from. 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.