# 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

**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

transpilerwould analyze our code and rewrite`into`

height ?? 100`.`

(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.

Babelis 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,

is a function that “cuts off” the decimal part of a number, e.g **Math.trunc(n)**

.**Math.trunc(1.23) = 1**

In some (very outdated) JavaScript engines, there’s no

, so such code will fail.**Math.trunc**

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

is a script that implements it, like this:**Math.trunc**

`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.