What are Polyfills and Transpilers in JavaScript?

polyfills and transpilers in javascript

Image by PublicDomainPictures from Pixabay

Javascript is continuously evolving since its debut in 1995. While this development happens, it is uncertain that these new features will work in every browser(and javascript engine, of course!). To make sure that newly released features are backward compatible with all the existing browsers, there are 2 techniques available – Polyfills and Transpilers. Let’s see what are polyfills and transpilers in JavaScript.

Polyfills

Polyfills in javascript provides a way to run new functionalities of javascript on very old and outdated browsers(javascript engines!). A code snippet that adds a new or missing feature to the script is called polyfill.

There are 2 libraries available to implement polyfill:

core js

core-js is a modular standard library for JavaScript that provides polyfills for many ECMAScript features.

polyfill.io

This is a polyfill service that includes only necesarry polyfills for the user specific browser. It is benificial as it includes only required polyfills and not the complete bunch of new features.

Example

if (!Math.trunc) {
Math.trunc = function(value) {
if (isNaN(value)) {
return NaN;
}
if (value > 0) {
return Math.floor(value);
}
return Math.ceil(value);
};
}

In this example, we first check if the Math.trunc method is not already defined in the browser. If it is not defined, we define a new function that emulates the behavior of the Math.trunc method.

Transpilers

Transpilers in javascript is a tool that translates source code from one version to another version. It parses the source code and converts it to old javascript engine compatible. It generally transfers latest ES6 code to ES5 and older version.

There are some tools available to “transpile” or convert code to older browser compatible codes, one such tool is babel.

Let’s assume you have following code:

const website = () => {
  let name= 'Codetopology';
  console.log(name);
};
website();

Babel will convert above code to following code:

var website = function website() {
  var name = 'Codetopology';
  console.log(name);
};

website();

Leave a Reply

Your email address will not be published. Required fields are marked *