What is the V8 engine? The V8 engine is a runtime environment that executes JavaScript code. Originally developed for Google Chrome, it is also integrated into Node.js. Most of the V8 engine is written in C++, and it can be embedded into any C++ program. When JavaScript code is executed in the V8 engine, it follows these steps:

  1. Parsing: The JavaScript code is first broken down into lexical tokens. For example, in the code let a = 5; let is one token, a is another token,= is another token, and 5 is another token. This process is known as tokenisation.
  2. AST (Abstract Syntax Tree) Generation: After tokenisation, the tokens are arranged into an Abstract Syntax Tree (AST). If the AST cannot be generated due to errors in the code, a syntax error is reported.
  3. Interpretation and Compilation: The AST is then passed to the Ignition Interpreter, which decides whether certain parts of the code should be converted to bytecode or sent to the TurboFan compiler. For example, code that is frequently executed, such as a function that is called repeatedly, may be passed to the TurboFan compiler for optimisation.

Execution and Optimisation: The code converted to bytecode is executed. The code sent to the TurboFan compiler is further optimised. However, if the assumptions made during optimisation no longer hold (e.g., the types of inputs change), the code may be de-optimised and sent back to the Ignition Interpreter for re-evaluation.

For example, if a function sum(a, b) was initially optimised for handling numbers, but later receives strings as input, the code would be de-optimised and re-evaluated by the interpreter. After re-evaluation, it might be optimised again by the TurboFan compiler, depending on the new input types. This entire process, from AST generation to execution within the V8 engine, is part of a broader technique called Just-In-Time (JIT) compilation. The V8 engine plays a crucial role in both Node.js and Google Chrome by continuously optimising code execution for better performance. Significant improvements, such as the Ignition Interpreter and TurboFan compiler, were introduced in 2017 to enhance performance in newer versions of Node.js.Other JavaScript engines used in browsers like Microsoft Edge and Safari follow similar processes, though their internal implementations may differ.