Polyfills and Transpilers in JavaScript

How to make out modern code work on older engines that don’t understand recent features yet? There are two tools that help them to understand.

1. Transpilers

A transpiler would analyze our code and rewrite height ?? 100 into (height !== undefined && height !== null) ? height : 100.

Now the rewritten code is suitable for older JavaScript engines.

Usually, a developer runs the transpiler on their own computer and then deploys the transpiled code to the server.

Babel is one of the most prominent transpilers out there.

Modern project build systems, such as webpack, provide the means to run transpiler automatically on every code change, so it’s very easy to integrate into the development process.

2. Polyfills

For example, Math.trunc(n) is a function that “cuts off” the decimal part of a number, e.g Math.trunc(1.23) = 1.

In some (very outdated) JavaScript engines, there’s no Math.trunc, so such code will fail.

As we’re talking about new functions, not syntax changes, there’s no need to transpile anything here. We just need to declare the missing function.

A script that updates/adds new functions is called “polyfill”. It “fills in” the gap and adds missing implementations.

For this particular case, the polyfill for Math.trunc is a script that implements it, like this:

if (!Math.trunc) { // if no such function
// implement it
Math.trunc = function(number) {
// Math.ceil and Math.floor exist even in ancient JavaScript engines
// they are covered later in the tutorial
return number < 0 ? Math.ceil(number) : Math.floor(number);
};
}

JavaScript is a highly dynamic language, scripts may add/modify any functions, even including built-in ones.

--

--

Developer with 3 yrs of industrial experience in developing scalable web applications.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.