Polyfill — Explained with Examples
Polyfill is a piece of code (usually JavaScript) that provides modern functionality on older browsers that do not natively support it. The term, coined by Remy Sharp, comes from “polyfilla” (a British product that fills cracks and holes) — the polyfill fills the gap between modern API expectations and legacy environment capabilities.
Polyfills are typically conditionally loaded: first check if the browser already supports the feature (e.g., typeof Array.prototype.flat === 'function'), and only inject the implementation if missing. Popular polyfill libraries include core-js (standard library features) and whatwg-fetch (Fetch API). Transpilers like Babel and Transpiler tools often work alongside polyfills: the transpiler converts syntax, the polyfill adds missing APIs.
Real-world analogy. A polyfill is like a universal power plug adapter. Your laptop expects a modern USB-C port (new browser API), but the hotel room only has old USB-A (older browser). You plug in an adapter (polyfill) that converts between the two — the laptop works exactly the same, but the adapter fills the compatibility gap.
Example (core-js polyfill for Array.flat):
// Check if native flat exists
if (!Array.prototype.flat) {
Array.prototype.flat = function(depth = 1) {
// Custom implementation...
// core-js provides this automatically
};
}
// Usage — works identically in old and new browsers
[1, [2, [3]]].flat(2); // [1, 2, 3]
Related terms: Transpiler, Compiled vs Interpreted, Progressive Enhancement, V8 Engine, Babel
Related tutorial: Polyfills Guide
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro