DEV Community

Cover image for Understanding the Key Concepts of Compilation in JavaScript
Daniel Joo
Daniel Joo

Posted on

Understanding the Key Concepts of Compilation in JavaScript

JavaScript can be best described as a compiled language. One may ask, "What is a compiled language?" Simply put, compilation is when code is transformed, through a series of steps, into instructions that your computer can then execute. During compilation, the entirety of the code is changed all at once. JS programs are run through two phases: compilation and execution. The programs are compiled before they are executed.

Compilation is important to consider and learn because it is during compilation that scope is determined. The scope, in turn, affects how the program is executed. Compilation broadly consists of three stages: Tokenizing/lexing, parsing, and code generation.

First, tokenizing/lexing is when the code is split up into meaningful chunks. For example, var c = 0 can be split up into the tokens var, c, =, 0.

Parsing is when these tokens are collected and formed into the Abstract Syntax Tree (AST). The AST can be describes as the grammatical structure of the program. According to Wikipedia, it is "a tree representation of the abstract syntactic structure of source code written in a programming language." To simply put, it represents the structure of the code. Lastly, during code generation, the AST is transformed into executable code.

So what exactly is the significance of compilation on how code is executed? Is there actual proof of compilation? Consider the code below.

var month = "It is March, 2020.";

console.log(month);

var month = ."It is March 14, 2020.";
// SyntaxError: unexpected token .

When this program is run, the console.log statement is in fact, not executed. This is because of the syntax error, which comes from the period, in the redeclaration of var month. This shows how the code is first compiled and then executed. Otherwise, the console.log statement would have been executed and then the error would have appeared.

Top comments (0)