Introduction to Compilers, Transpilers and Babel

Introduction to Compilers, Transpilers and Babel

·

2 min read

What is Babel? I was asked this question in a mock interview and while I have heard of Babel, I didn't know what exactly it does. So I decided to explore Babel and related topics and this blog is compilation of my learnings.

Keywords

High Level Language: The language we, developers, use for writing a program. It is human readable, programmer friendly language with actual working details abstracted. Eg. JavaScript, Python

Low Level Language: It is the machine readable language or the language in which the machine takes instructions. The level of abstraction is much lower or zero.

Compiler

The code we write in High level language is greek to the computer. Computer understands 0s and 1s. Compiler is a tool that solves this problem. It transforms the code from High Level Language to machine readable Low Level Language. Do note that the abstraction level in source language and target language is different.

Transpiler

A Transpiler is a source-to-source compiler. It transforms the code to another language at same abstraction level. Eg. From ES6 to ES5, from Typescript to Javascript

Transpiler and Compiler are similar and different at the same time. While a Compiler handles languages with different abstraction levels, a Transpiler deals with languages at the same abstraction level. Thus, Transpiler is a special type of Compiler.

Babel

Babel is a popular transpiler that enables older browsers to run latest version of JavaScript.

But why do browsers need to be explicitly enabled to run latest JS?

For example, ES6 introduced many new changes in JavaScript like arrow functions, async await etc-. Browsers won't be able to interpret these changes in syntax unless browser manufacturers update them to support ES6. Even after that, older versions of browsers should be able to handle ES6. When browsers can't keep up with the changing standards, Babel comes to the rescue. It transforms syntax, polyfills missing features and does host of other things to convert new language features to older ones.

Eg. ES6 syntax not supported by all browsers

const add = (a,b) => a+b

Babel transforms it to

function add(a,b){
  return a+b
}

Summary

  • Compilers transform code from one language to another at different level of abstraction
  • Transpilers transform code from one language to another at same level of abstraction
  • Babel is a transpiler used to convert features in new version of JavaScript to that of older versions and support backward compatibility