27 February 2024
When you run your JavaScript code, it compiles and gets executed in your browser or server. How does your JavaScript code compile into machine code? Let's dive a little deeper to learn more about how JavaScript works.
A JS Engine is a piece of program that executes your JS code. So that means JS can execute not only on a browser but also on any piece of device which has a JS Engine. Every browser has its own version of a JS Engine. For Example...
Earlier, JS was only limited to running on browsers as a client-side language only. With Node.js, JS can also be used on the server, and to execute JS, Node.js uses the V8 engine. In simple terms,
[Fig 1.1] JS Engine
An Execution context (EC) is where your JS code will get executed, so all the necessary information about your code being run will be stored inside the EC. Each EC has two phases.
When the JS Engine executes your JS Code for the first time, before even executing your code, it will create the Global Execution Context which is default EC and contain top-level code. During this Phase JS Engine will do following tasks:
So each Execution Context store:
During the execution phase, the Engine will run JS code line by line, assign values to variables, and execute functions. For each function call, the JS Engine will create a new context, known as the Function Execution Context, and push it into the call stack. Unlike the Global EC, the Function EC represents the function's local scope, so it will only have local variables.
The JS file enters the engine and the parser parses the file, performing lexical analysis to break the code into tokens, which will be used in the creation of an Abstract Syntax Tree (AST).
Now, the generated AST is passed down to the interpreter, which generates the unoptimized code, allowing execution to start with no delay. The profilerwatches the code as it runs and identifies areas where optimization is needed. The profiler then passes that code to the compiler which performs optimization and generates optimized code that can replace its counterpart in the non-optimized code generated by the interpreter.
As the profiler and compiler constantly make changes to the bytecode, the JavaScript execution performance gradually improves.
[Fig 1.2] V8 Engine
In V8 Engine, JS is interpreted by an interpreter called Ignition as well as compiled by a JIT-optimized compiler called TurboFan
JS Engine runs inside an environment, which provides additional features to the scripts that we can use at runtime.
[Fig 1.3] JS Runtime
Let's understand the working of JS Runtime via example:
[Fig 1.4] JS Runtime Visualize via loupe
Last Updated
27 February 2024