What is a polyfill?
A polyfill is code that implements a modern feature for older environments that lack it, so your code runs everywhere.
How — it checks whether a feature exists and defines it if missing.
Versus transpiling — polyfills add missing APIs (like Promise); transpilers (Babel) convert new syntax to old.
Tools like core-js provide polyfills automatically based on your browser targets.
// Polyfill for Array.prototype.includes
if (!Array.prototype.includes) {
Array.prototype.includes = function(value, fromIndex) {
if (this == null) throw new TypeError('Cannot call on null/undefined');
const arr = Object(this);
const len = arr.length >>> 0;
if (len === 0) return false;
const start = fromIndex || 0;
for (let i = Math.max(start >= 0 ? start : len + start, 0); i < len; i++) {
if (arr[i] === value || (Number.isNaN(arr[i]) && Number.isNaN(value))) {
return true;
}
}
return false;
};
}
// Usage (works on old browsers now)
[1, 2, 3].includes(2); // trueThe polyfill first checks if includes already exists (if (!Array.prototype.includes)). If not, it adds the implementation.
The implementation handles NaN correctly (NaN === NaN is false, but includes should find NaN). The >>> 0 converts length to an unsigned 32-bit integer (edge case handling).
Show the if-not-exists check before adding the polyfill. Know the difference: polyfill = missing API, transpiler = new syntax.
Babel does both (transpiles syntax + includes core-js polyfills). Modern approach: use core-js for polyfills and Babel for transpilation.