What are polyfills and transpilers in JavaScript?

There are situations where we might have encountered that our code runs in one browser and not in another. This may be because one of the browsers may not be updated with latest features. Now let’s see about polyfills and transpilers.

Polyfills and transpilers:

JavaScript like many programming languages evolves steadily. To make our latest code work on old engines that don’t understand the latest features we have two tools : polyfills and transpilers.

Transpilers:

Term transpiling is the union of transformation and compiling. Transpiler is a piece of code or plugin that translates (‘read and understand’) one source code to another source code. It parse the modern code  and rewrite it using older syntax of that language that will work in older engines.

Babel is one of the most used transpiler

Project build systems like Webpack or parcel allows us to automatically run transpiler on every code change so it’s easy to integrate transpiler into our development process. Developers run their transpiler in their own computer or in the cloud and then deploys the transpiled code to the server.

Example:

Nullish coalescing operator is introduced in 2020. So older browser transforms our code as follows:

// before running the transpiler
num = num ?? 150;
// after running the transpiler
num = (num !== undefined && num !== null) ? num: 150;

Polyfills:

At times when new functionality is not available in old outdated browser engines. The code that uses new functionality won’t work. To fill this gap, comes polyfills.

Polyfill is a piece of code that can add, update a feature that engine may lack.

A polyfill is a browser fallback, made in JavaScript that allows functionality you expect to work in modern browsers to work in older browsers.

Example:

filter() method is introduced in ES5 and some outdated browser doesnot support

const arr = [1, 2, 3, 4, 5, 6];
const filtered = arr.filter((e) => e % 2 === 0); // filter outs the even number
console.log(filtered); // [2, 4, 6]
Polyfill for filter():
Array.prototype.filter = function (callback) {
  // Store the new array
  const result = [];
  for (let i = 0; i < this.length; i++) {
  // call the callback with the current element, index, and context.
  //if it passes the text then add the element in the new array.
    if (callback(this[i], i, this)) {
      result.push(this[i]);
    }
  }
  //return the array
  return result
}
Two interesting polyfill libraries are:
  • core.js that supports a lot, allows to include only needed features.
  • polyfill.io service that provides a script with polyfills, depending on the features and user’s browser.