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 keywords, identifiers, literals, and symbols, variable declaration, function declaration etc. This is known as tokenization.
During this scanning, the engine also checks syntax errors too and immediately stops execution if it finds one and throws the error.
eg of syntax error ->
Missing or mismatched parentheses or brackets
Invalid syntax for statements or expressions
missing initialization in const declaration
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.
visualize AST tree via https://astexplorer.net/
Step-2: Just-In-Time(JIT) compilation
Modern JS is neither an interpreted language nor a compiled one. Modern JS engine uses JIT compilation to convert generated AST tree into machine code.
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 have just learned fundamental concepts related to JS execution. Share your knowledge. Teach someone and it will help you understand this for a longer time. Keep following for more such articles.
Further Read-
Upcoming articles
Settimeout intricacies
How JS handles async events
Functions in JS