Polyfills and Transpilers in JavaScript

Abhay Jain
2 min readDec 29, 2020

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

Transpiler is a special piece of software that can parse (“read and understand”) modern code, and rewrite it using older syntax constructs so that the result would be the same.

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

New language features may include not only syntax constructs and operators but also built-in functions.

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.



Abhay Jain

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