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.
Write Function.prototype.myBind(thisArg, ...presetArgs), which works like bind without calling it (call and apply are fine). It returns a new function, the bound function, and doesn't call anything yet.
Calling the bound function calls the original with this set to thisArg, and with presetArgs followed by the arguments of this call. It returns the original's result. The bound this is fixed: calling the bound function as a method, or with call, doesn't change it.
Calling the bound function with new ignores thisArg: it does what new on the original would do with the same arguments. So the result is an instance of the original, and if the original returns an object, that object is the result.
If myBind is used on something that isn't a function, throw a TypeError.
const user = { name: "Ada" };
function greet(greeting, mark) {
return greeting + ", " + this.name + mark;
}
const hi = greet.myBind(user, "Hi");
hi("!"); // "Hi, Ada!"
function Point(x, y) {
this.x = x;
this.y = y;
}
const OnYAxis = Point.myBind({ ignored: true }, 0);
const p = new OnYAxis(5); // Point { x: 0, y: 5 }
p instanceof Point; // true
const fn = spy();
const user = { name: "Ada" };
const bound = fn.myBind(user);
expect(typeof bound).toBe("function");
expect(fn).not.toHaveBeenCalled();
bound();
expect(fn).toHaveBeenCalledTimes(1);
expect(fn.calls[0].this).toBe(user);
const fn = spy();
fn.myBind(null, 1, 2)(3, 4);
expect(fn).toHaveBeenCalledWith(1, 2, 3, 4);
function add(a, b) {
return this.base + a + b;
}
expect(add.myBind({ base: 10 }, 1)(2)).toBe(13);
const fn = spy();
const user = { name: "Ada" };
const bound = fn.myBind(user);
const other = { method: bound };
other.method();
bound.call({ name: "someone else" });
expect(fn.calls[0].this).toBe(user);
expect(fn.calls[1].this).toBe(user);
function Point(x, y) {
this.x = x;
this.y = y;
}
const ignored = {};
const Bound = Point.myBind(ignored, 1);
const point = new Bound(2);
expect(point).not.toBe(ignored);
expect(point.x).toBe(1);
expect(point.y).toBe(2);
expect(Object.keys(ignored)).toEqual([]);
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.sum = function () {
return this.x + this.y;
};
const Bound = Point.myBind(null, 1);
const point = new Bound(2);
expect(point).toBeInstanceOf(Point);
expect(point.sum()).toBe(3);
const made = { made: true };
function Factory() {
this.ignored = true;
return made;
}
const Bound = Factory.myBind({});
expect(new Bound()).toBe(made);
const notAFunction = { myBind: Function.prototype.myBind };
expect(() => notAFunction.myBind({})).toThrow(TypeError);
const builtIn = Function.prototype.bind;
Function.prototype.bind = function () {
throw new Error("myBind called the built-in bind");
};
let result;
try {
const add = function (a, b) {
return this.base + a + b;
};
result = add.myBind({ base: 1 }, 2)(3);
} finally {
Function.prototype.bind = builtIn;
}
expect(result).toBe(6);
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 Function.prototype.bind. 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.