What is Transpiler? Why do we need them in Javascript

What is Transpiler? Why do we need them in Javascript

I recently came across the JavaScript Jargon "Transpiler" at neogCamp, so thought of writing a blog on it.

Transapiler

History of JavaScript

JavaScript is a very different language as it doesn't have a compiler and every browser has its JavaScript. Node, as well as browser, are run times, not compilers. There were times browsers had their version of JavaScript. The problem with Browser-provided web APIs is that they will work fine on that particular browser, But code might crash in different browsers. Everyone in the Javascript community unified to create a standard body known as ECMAScript. There are many versions of JavaScript ES1, ES2, ES5, ES6 e.t.c. Presently, many browsers fully support ES5.

Need of Transpiling

These days browsers fully support ES5, but code with ES6 or ES6+ syntax may not run. So to run the Application in every browser, we use Transpilers. It's better to be safe than sorry.

What is Transpiling

Transpiler translates a program of one language (A) into an equivalent program in another language (B) that has the same level of abstraction.

Example: Let's write a program to find the maximum and minimum out of two given numbers.

//ES6
const num1 = 129;
const num2 = 251;

const max = (num1, num2) => num1 > num2 ? num1 : num2;

console.log(`maximum  of ${num1} and ${num2} `, max(num1, num2));

If we run this program in a browser that doesn't support ES6, we will be getting errors. To run the above code in a browser that supports ES5, we need to make a few changes.

"use strict";

var num1 = 129;
var num2 = 251;

var max = function max(num1, num2) {
  return num1 > num2 ? num1 : num2;
};

console.log("maximum  of " + num1 + " and " + num2 + " ", max(num1, num2));

While developing huge applications, it's not possible to make changes manually. That's why we use Babel. Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments.