Is JavaScript compiled or interpreted? The answer is: **both**. Modern JS engines like Google's V8 (used in Chrome and Node.js) use a technique called **Just-In-Time (JIT) Compilation** to run code at blistering speeds.
How the V8 Engine Works Under the Hood
V8's compilation pipeline is divided into several main stages:
1. Parsing and AST Generation
The JavaScript source code is parsed by a lexical analyzer into tokens, which are then used to build an **Abstract Syntax Tree (AST)**, a structured tree representation of the code's syntax.
2. Bytecode Generation (Ignition Interpreter)
The parser feeds the AST into V8's interpreter, named Ignition. Ignition compiles the AST into lightweight **bytecode**. This bytecode can be executed instantly, giving the application a fast startup time.
3. Optimization (TurboFan Compiler)
While the bytecode is running, a profiler monitors which parts of the code are run frequently (so-called "hot spots"). This hot code is sent to V8's optimizing compiler, TurboFan, which compiles it directly into highly optimized machine code, boosting speed.
4. Deoptimization
JavaScript is dynamically typed. If TurboFan makes assumptions about a function's arguments (e.g., assuming a parameter is always an integer) and the code changes types later (e.g., passing a string), V8 will deoptimize and revert to Ignition interpreter's bytecode execution.