2 min read

Polyfills and Transpilers

As JavaScript evolves (ES6, ES2020, etc.), new features are added to the language. However, not all browsers support these new features immediately. To ensure your code runs on older browsers (like Internet Explorer or older versions of Safari), developers use Polyfills and Transpilers.

1. Transpilers (Source-to-Source Compilers)

A Transpiler (Transformation + Compiler) takes modern JavaScript code (ES6+) and converts it into an older version of JavaScript (usually ES5) that can run in any browser.

  • What it handles: Syntax changes (new keywords, new grammar).
  • Example: Arrow functions, Classes, let/const, Destructuring.
  • Popular Tool: Babel.

Example

Modern Code (Input):

const add = (a, b) => a + b;

Transpiled Code (Output - ES5):

var add = function(a, b) {
  return a + b;
};

The transpiler rewrites the syntax so the browser understands it.

2. Polyfills

A Polyfill is a piece of code (usually a JavaScript function) used to provide modern functionality on older browsers that do not natively support it.

  • What it handles: New functions, methods, or objects.
  • Example: Array.prototype.includes, Promise, fetch.
  • Popular Tool: core-js.

A transpiler cannot fix missing methods. If you use myArray.includes(1), Babel won't change it because the syntax is valid in ES5 (calling a method). However, if the browser doesn't have the .includes method on Arrays, it will crash. A polyfill adds that method to the Array prototype.

Example

Modern Code:

if (!Array.prototype.includes) {
  Array.prototype.includes = function(searchElement) {
    // Implementation of the includes method...
    // (Iterate over array and return true if found)
  };
}

3. Summary: The Difference

Feature Transpiler (Babel) Polyfill
Handles Syntax (Grammar) Built-in Functions/Objects (API)
Examples =>, class, import Promise, .map(), Object.assign()
Action Rewrites code Adds missing code
Analogy Translating English to Old English. Adding a definition to a dictionary.

programming/javascript/vanilla/javascript programming/javascript/vanilla/es6-features