A polyfill is code that implements a missing built-in API (e.g. Array.prototype.at, structuredClone, Promise.withResolvers) so that newer code runs in older environments. It only works for things that can be expressed in existing JavaScript. New syntax (optional chaining, class fields) cannot be polyfilled; it must be transpiled (Babel, SWC, esbuild, TypeScript). Polyfills trade compatibility for bundle size and correctness risk, so ship them deliberately, based on your browser targets.
if (!Array.prototype.at) {
Object.defineProperty(Array.prototype, 'at', {
value: function at(index) {
const len = this.length >>> 0;
let i = Math.trunc(index) || 0;
if (i < 0) i += len;
return i < 0 || i >= len ? undefined : this[i];
},
writable: true,
configurable: true,
enumerable: false, // built-in methods are non-enumerable; don't break for…in
});
}
Good polyfills:
length/name.for…in loops.| What it handles | Example | |
|---|---|---|
| Polyfill | Missing runtime APIs, patched onto globals | core-js adding Object.groupBy |
| Transpiler | New syntax rewritten to old syntax | a?.b → a == null ? void 0 : a.b |
| Ponyfill | Same API exported as a module, without touching globals | import groupBy from 'object.groupby' |
Some features need both (async functions need a transpile step plus a Promise and generator runtime). Some can't be done faithfully at all: Proxy, WeakRef, true private #fields without WeakMap, and most new CSS or rendering capabilities.
defaults and supports es6-module). Babel's preset-env with useBuiltIns: 'usage' and core-js then injects only the polyfills that your code uses and your targets lack.@vitejs/plugin-legacy automate this with <script type="module"> / nomodule.polyfill.io domain changed hands and served malicious code to many sites. Self-host polyfills or bundle them, ideally with Subresource Integrity on any third-party script.core-js can add tens of kilobytes. Audit with bundle analysers.Array.prototype.flatten led to the method being named flat).core-js, not "include everything".Spotted a mistake or a rights concern? Report an issue