Deep dive:-  Conversion of  Javascript code into machine code by JavaScript EnginE

Deep dive:- Conversion of Javascript code into machine code by JavaScript EnginE

This article is written as part of the series where I am writing the whole process of how Javascript files are executed by browsers. This is the second article. The first article is here.

The JS engine executes JS code. Every browser as well as node.js has its own JS engine to perform the execution of JS.

As soon as the script file loads onto the browser, the JS engine takes over to execute the code in the following steps-

Step -1: Parsing of JS code

Parsing means reading. The JS engine scans the code line by line and first split up each line of code into pieces that are meaningful to the language like variable declaration, function declaration etc. During this scanning, the engine also checks syntax errors too and immediately stops execution if it finds one and throws the error.

const a;
a = 20; // Syntex error: Missing initialization in const declaration

If there is no error, all these pieces of code are saved into a tree-type data structure called AST(Abstraction syntax tree). This tree will later be used to generate the machine code.

Step-2: Just-In-Time(JIT) compilation

Modern JS is neither an interpreted language nor compiled one. Modern JS engine uses JIT compilation to convert generated AST tree into machine code.

Pink Black White Red Photocentric Feminine Lifestyle Beauty Fashion YouTube Channel Art Banner (2).png

JIT compilation means the entire code is first compiled and converted into machine code. But at the very beginning, this compiler creates a very unoptimized version of machine code to execute it as fast as possible. So, in the background, this unoptimized code is recursively passed through optimization steps and then again recompiled. This step can be done multiple times. After each optimization step, the earlier machine code is swept away for the new optimized code without ever stopping the execution of the code. This makes modern JS browsers like google chrome very fast. In this article, we are not digging deep into optimization steps. Feel free to read this article by Jim Clark

In some JS engine, this process is AOT(Ahead of time) compilation.

Once these two steps are done, the execution of machine code by the JS engine happens inside the call stack more about which you can read here.

That's it, folks. You just have learned fundamental concepts related to JS execution. Share your knowledge. Teach someone and it will help you in learning this for a longer time. Keep following for more such articles.

Further Read-

  1. Conversion of high-level JS code to machine code by browser

  2. The one article about Execution Context to rule them all.

  3. The one article about scopes to rule them all.

  4. The one article about Hoisting to rule them all.

Upcoming articles

  1. Settimeout intricacies

  2. How JS handles async events

  3. Functions in JS