A Polyfill Adds Missing APIs at Runtime, a Transpiler Rewrites New Syntax at Build Time

In progress

Running modern JavaScript on older engines needs two different tools. A transpiler (Babel, TypeScript's tsc, esbuild) rewrites source code into equivalent code in another language or an older version of the same one, at build time: arrow functions become functions, TypeScript becomes JavaScript. A polyfill (core-js is the best known collection) is code loaded at runtime that implements a missing built-in, such as Array.prototype.includes or Promise, only if the engine lacks it. Syntax can't be polyfilled, and missing APIs can't be transpiled away.

Which Problem Each Solves

Transpiler Polyfill
When at build time when the page runs
Fixes syntax the engine can't parse (=>, class, template literals, type annotations) functions and objects the engine doesn't provide (fetch, Array.prototype.flat)
Output rewritten source files extra code that patches globals if they're missing
Example Babel turns a class declaration into a constructor function core-js adds Array.prototype.includes on old browsers

A modern build usually does both: transpile to the syntax the target browsers understand, then include only the polyfills those browsers need (Babel's preset-env with a browserslist target can do the selection).

References

Review cards

Flashcard When does a transpiler run, and when does a polyfill?

A transpiler at build time, rewriting source files. A polyfill at runtime, in the page, adding a built-in only if the engine lacks it.

Flashcard Why can't a polyfill add support for arrow functions?

An engine that can't parse => rejects the script before any code runs, so runtime code can't help: syntax needs a transpiler. Missing APIs (Array.prototype.includes) are the polyfill's job.

Flashcard Why does a modern build use both a transpiler and polyfills, and how does it keep polyfills small?

Each fixes what the other can't: syntax vs missing APIs. Babel's preset-env with a browserslist target transpiles to what those browsers parse and includes only the polyfills they need.