In Chapter 02: JS on the Server you saw the short version: V8 parses your code, interprets it, and optimizes the hot parts. This chapter opens each step up. You'll see real bytecode, learn why some code is faster than other code that does the same thing, and understand how V8 cleans up memory.
In this chapter you'll learn
- how V8 parses code: tokens and the AST
- what bytecode is, and how the Ignition interpreter runs it
- how V8 finds "hot" code and compiles it with TurboFan (plus Sparkplug and Maglev)
- what deoptimization is, and how to write code that stays fast
- how garbage collection works: stack vs heap, mark-and-sweep, generations
Before you start: read Chapter 02: JS on the Server and Chapter 06: libuv & async IO.

Step 1: Parsing
Before V8 can run anything, it has to understand your code.
Lexical analysis (tokenizing)
The scanner reads your code character by character and groups the characters into tokens: the smallest meaningful pieces.
const sum = a + 10;const sum = a + 10;becomes the tokens:
const sum = a + 10 ;
keyword name op name op number punctuationconst sum = a + 10 ;
keyword name op name op number punctuationSyntax analysis (building the AST)
The parser arranges the tokens into an Abstract Syntax Tree (AST): a tree that represents the structure and meaning of the code.
VariableDeclaration (const)
└── sum =
└── BinaryExpression (+)
├── Identifier: a
└── NumericLiteral: 10VariableDeclaration (const)
└── sum =
└── BinaryExpression (+)
├── Identifier: a
└── NumericLiteral: 10If the tokens don't form valid JavaScript (say, const = 5), the parser stops with a SyntaxError. That's why a syntax error anywhere in a file prevents any of it from running.
Paste any code into astexplorer.net to see its AST. Tools like ESLint, Prettier, Babel and TypeScript all work on ASTs.
Lazy parsing
Parsing takes time. V8 doesn't fully parse functions that haven't been called yet; it pre-parses them (just enough to check the syntax) and parses them fully on their first call. This makes startup faster for big programs.
Step 2: Ignition, the interpreter
The Ignition interpreter turns the AST into bytecode and starts running it immediately.
Bytecode is a compact, low-level set of instructions for V8's own virtual machine. It isn't machine code (the CPU can't run it directly), but it's much simpler than JavaScript and quick to execute.
You can see it yourself. For this function:
function add(a, b) {
return a + b;
}
console.log(add(2, 3));function add(a, b) {
return a + b;
}
console.log(add(2, 3));run node --print-bytecode --print-bytecode-filter=add add.js, and V8 prints (shortened, from Node.js 22):
[generated bytecode for function: add]
Parameter count 3
Ldar a1 ← load argument b into the accumulator
Add a0, [0] ← add argument a to it; [0] is a feedback slot
Return ← return the accumulator[generated bytecode for function: add]
Parameter count 3
Ldar a1 ← load argument b into the accumulator
Add a0, [0] ← add argument a to it; [0] is a feedback slot
Return ← return the accumulatorThree tiny instructions. Notice [0]: that's a feedback slot where Ignition records what kinds of values it actually sees (here: "always two small integers"). This is where optimization begins.
Step 3: Profiling and the optimizing compilers
While bytecode runs, V8 keeps statistics: how often each function runs and which types it sees. Functions that run a lot are called hot.
Running hot code in an interpreter wastes time, so V8 compiles it to machine code. Modern V8 has several compiler tiers, each faster to run but slower to compile:
| Tier | What it does | When it's used |
|---|---|---|
| Ignition | interprets bytecode | everything starts here |
| Sparkplug | turns bytecode into simple machine code, almost instantly, without optimizing | "warm" functions |
| Maglev | quick optimizing compiler using type feedback | "hot" functions |
| TurboFan | V8's strongest optimizer: inlining, removing checks, specialized machine code | "very hot" functions |
The older textbook picture (and the original course lectures) shows just Ignition → TurboFan. That's still the right mental model; Sparkplug (2021) and Maglev (2023) are stepping stones added in between.
How TurboFan makes code fast: speculation
JavaScript is dynamically typed: a + b could mean adding numbers, joining strings, or calling valueOf on objects. Checking all that on every call is slow.
TurboFan uses the type feedback collected earlier and speculates: "add has been called 10,000 times, always with two integers. I'll compile a version that adds integers directly, with a quick check that the arguments really are integers."
Deoptimization
What if the guess turns out wrong?
function add(a, b) {
return a + b;
}
for (let i = 0; i < 100000; i++) {
add(i, 1); // always numbers → V8 optimizes add() for numbers
}
add("Namaste ", "Node"); // a string! The check fails → deoptimizefunction add(a, b) {
return a + b;
}
for (let i = 0; i < 100000; i++) {
add(i, 1); // always numbers → V8 optimizes add() for numbers
}
add("Namaste ", "Node"); // a string! The check fails → deoptimizeWhen the quick check fails, V8 throws away the optimized machine code and goes back to bytecode. This is called deoptimization (or a "bailout"). V8 may optimize again later, this time for both numbers and strings, but the result is less specialized and slower.
Hidden classes (shapes) and inline caches
V8 also gives every object an internal hidden class (also called a shape or map) describing its layout: which properties it has and in what order. Objects with the same shape can share optimized code, using inline caches: once V8 knows where user.name lives for a shape, it remembers that location.
// ✅ Same shape: properties added in the same order
const u1 = { name: "Akshay", age: 30 };
const u2 = { name: "Aditi", age: 25 };
// ⚠️ Different shapes: same properties, different order
const u3 = { age: 30, name: "Rohan" };
// ⚠️ Shape changes later
const u4 = { name: "Neha" };
u4.age = 22; // adds a new shape transition
delete u1.name; // deleting a property (not the last one) can force a slower "dictionary" mode// ✅ Same shape: properties added in the same order
const u1 = { name: "Akshay", age: 30 };
const u2 = { name: "Aditi", age: 25 };
// ⚠️ Different shapes: same properties, different order
const u3 = { age: 30, name: "Rohan" };
// ⚠️ Shape changes later
const u4 = { name: "Neha" };
u4.age = 22; // adds a new shape transition
delete u1.name; // deleting a property (not the last one) can force a slower "dictionary" modeYou don't need to obsess over this, but these habits keep your code on the fast path:
- Initialize all properties of an object up front (for example in the constructor), in the same order.
- Don't change types: a variable that holds a number should keep holding numbers.
- Avoid
deleteon objects in hot code; set the property toundefinedornullinstead. - Keep arrays of one type:
[1, 2, 3]is faster than[1, "two", {}].
Step 4: Garbage collection
Stack vs heap
V8 stores data in two places:
- Stack: small, fast, automatically cleaned when a function returns. It holds function calls (the call stack from Chapter 06: libuv & async IO), primitive local values and references (pointers) to objects.
- Heap: a large area for objects, arrays, functions and strings. Things here can outlive the function that created them, so something has to clean them up.
That something is the garbage collector (GC).
Reachability and mark-and-sweep
The GC's rule is simple: an object is alive if your program can still reach it, starting from the roots (global variables and the current call stack) and following references.
The basic algorithm is mark-and-sweep:
- Mark: start at the roots and follow every reference, marking each object reached.
- Sweep: anything not marked is unreachable, so its memory is freed.
let user = { name: "Akshay" }; // reachable through the variable `user`
user = null; // nothing points to the object anymore → garbagelet user = { name: "Akshay" }; // reachable through the variable `user`
user = null; // nothing points to the object anymore → garbageGenerations: most objects die young
Most objects are short-lived: temporary arrays, strings built in a loop, objects returned from a function and immediately used. V8's collector (named Orinoco) is generational:
- Young generation: a small area where new objects are created. It's cleaned very often and very quickly (a "scavenge").
- Old generation: objects that survive a couple of young-generation cleanups move here. It's cleaned less often with a full mark-sweep-compact (compacting moves objects together to avoid gaps).
Much of this work runs incrementally and on background threads, so pauses on your JavaScript thread stay short. GC is not a step that happens "at the end": it runs alongside your program the whole time.
Memory leaks still happen
The GC only frees unreachable objects. If you keep a reference by mistake, the memory stays used forever:
const cache = []; // a module-level (long-lived) array
app.get("/data", (req, res) => {
cache.push(req.body); // ❌ grows on every request, never cleared
res.send("ok");
});const cache = []; // a module-level (long-lived) array
app.get("/data", (req, res) => {
cache.push(req.body); // ❌ grows on every request, never cleared
res.send("ok");
});Common leaks: ever-growing arrays/maps used as caches, event listeners that are never removed, setInterval timers that are never cleared, and closures holding big objects.
By default, the old generation is limited (a few GB on 64-bit systems, depending on version and available memory). If a process really needs more, start it with node --max-old-space-size=4096 app.js (in MB). If memory keeps growing for no reason, you probably have a leak; take heap snapshots with Chrome DevTools (node --inspect app.js).

Key takeaways
- Parsing: code → tokens → AST. Syntax errors are caught here, before anything runs.
- Ignition turns the AST into bytecode and runs it immediately, collecting type feedback.
- Hot code is compiled to machine code: Sparkplug → Maglev → TurboFan, each more optimized.
- TurboFan speculates on types; when a guess fails, V8 deoptimizes back to bytecode.
- Objects have hidden classes. Same properties in the same order + stable types = faster code.
- GC frees unreachable objects with mark-and-sweep, using young and old generations. Leaks come from references you keep by accident.
Interview questions
Q1. Explain V8's code execution pipeline.
Source code is parsed into tokens and an AST. Ignition compiles the AST to bytecode and interprets it, recording type feedback. Frequently run ("hot") functions are compiled to machine code by faster tiers: Sparkplug (baseline), Maglev (mid-level optimizer) and TurboFan (top optimizer). If an optimization assumption breaks, the code is deoptimized back to bytecode. The garbage collector runs alongside all of this.
Q2. What is deoptimization?
Optimizing compilers like TurboFan generate machine code based on assumptions from past runs (for example "this argument is always an integer"), protected by quick checks. When a check fails at runtime, V8 discards the optimized code and continues in the bytecode interpreter. Frequent deoptimizations make code slower, which is why keeping types stable matters.
Q3. What are hidden classes in V8?
Hidden classes (also called shapes or maps) are V8's internal description of an object's layout: which properties it has and in which order. Objects with the same hidden class can share optimized property lookups (inline caches). Adding properties in different orders, adding them later, or using delete creates new hidden classes and slows lookups down.
Q4. How does garbage collection work in JavaScript?
The GC frees objects that are no longer reachable from the roots (globals and the call stack). V8 uses mark-and-sweep: mark everything reachable, then free the rest. It's generational: new objects go to a small young generation cleaned often and fast; survivors move to the old generation, which is cleaned less often with mark-sweep-compact. Much of the work is incremental or runs on background threads.
Q5. What is the difference between the stack and the heap?
The stack holds function call frames, primitive local values and references; it's small, fast and cleaned automatically when functions return. The heap holds objects, arrays, functions and strings; it's larger, and its memory is reclaimed by the garbage collector.
Q6. What causes memory leaks in Node.js, and how do you find them?
Typical causes: global or module-level caches that grow forever, event listeners that are never removed, uncleared setIntervals, and closures holding large objects. To find them, watch process.memoryUsage() over time, then take and compare heap snapshots in Chrome DevTools (node --inspect) to see which objects keep growing.
Q7. What is JIT compilation, and why is it useful for JavaScript?
Just-In-Time compilation compiles code to machine code while the program runs, instead of before. It suits JavaScript because types are only known at runtime: the engine can start quickly in an interpreter, observe real types, and then generate machine code specialized for how the code is actually used.
What's next
You now know how V8 runs your JavaScript, one call stack at a time. But who decides which callback runs next when many async operations finish? That's the job of the event loop, the heart of Node.js, in Chapter 09: libuv & event loop.