JavaScript Bytecode Explained: Complete Guide
Understand JavaScript bytecode in V8's Ignition interpreter. Covers bytecode format, register allocation, common bytecode instructions, constant pools, feedback vectors, how to read bytecode output, and the relationship between source code and generated bytecodes.
V8's Ignition interpreter executes JavaScript as bytecode, a compact instruction set that sits between source code and machine code. Understanding bytecode reveals exactly what the engine does with your code and why certain patterns perform better than others.
For how bytecode fits into the V8 compilation pipeline, see How the Google V8 Engine Compiles JavaScript.
Bytecode Format
Ignition uses a register-based bytecode format. Each bytecode instruction is one byte (the opcode) followed by zero or more operand bytes. An implicit accumulator register holds the result of the most recent operation.
// To see real V8 bytecode, run:
// node --print-bytecode --print-bytecode-filter=functionName script.js
// Simple assignment:
function assign() {
const x = 42;
return x;
}
// Bytecode:
// LdaSmi [42] // Load Small Integer 42 into accumulator
// Star0 // Store accumulator into register r0
// Ldar r0 // Load register r0 into accumulator
// Return // Return the accumulator value
// V8 actually optimizes this to:
// LdaSmi [42] // Load 42
// Return // Return it (r0 store/load eliminated)
// Arithmetic:
function add(a, b) {
return a + b;
}
// Bytecode:
// Ldar a1 // Load parameter b into accumulator
// Add a0, [0] // Add parameter a to accumulator, feedback slot [0]
// Return // Return result
// Key bytecode concepts:
// - ACCUMULATOR: Implicit register, most operations read/write it
// - REGISTERS: r0, r1, r2... for local variables
// - PARAMETERS: a0, a1, a2... for function arguments
// - FEEDBACK SLOTS: [0], [1]... for runtime type profiling
// - CONSTANT POOL: Stores strings, numbers, and other constants
// Bytecodes are compact: each instruction is typically 1-4 bytes
// A simple function compiles to 10-50 bytes of bytecode
// vs 100-500 bytes of machine codeRegister Allocation
// Ignition allocates registers for local variables and temporaries
function calculate(x) {
const doubled = x * 2; // r0 = x * 2
const tripled = x * 3; // r1 = x * 3
const sum = doubled + tripled; // r2 = r0 + r1
return sum;
}
// Bytecode:
// Ldar a0 // Load x into accumulator
// MulSmi [2], [0] // Multiply accumulator by 2, feedback slot [0]
// Star0 // Store result in r0 (doubled)
// Ldar a0 // Load x into accumulator
// MulSmi [3], [1] // Multiply by 3, feedback slot [1]
// Star1 // Store in r1 (tripled)
// Ldar r0 // Load doubled
// Add r1, [2] // Add tripled, feedback slot [2]
// Star2 // Store in r2 (sum)
// Return // Return accumulator (sum)
// REGISTER CONTEXT for closures
function outer() {
let count = 0; // Lives in Context (heap), not register
return function inner() {
count++; // Accesses Context, not a register
return count;
};
}
// Bytecode for inner():
// LdaCurrentContextSlot [2] // Load 'count' from context slot 2
// Inc [0] // Increment, feedback slot [0]
// StaCurrentContextSlot [2] // Store back to context slot 2
// Return // Return the incremented value
// Context variables are slower than register variables because
// they require memory access instead of register-to-register moves
// TEMPORARY REGISTERS for complex expressions
function complex(a, b, c) {
return (a + b) * (c - a);
// Needs a temporary to hold (a + b) while computing (c - a)
}
// Bytecode:
// Ldar a1 // Load b
// Add a0, [0] // a + b -> accumulator
// Star0 // Store (a + b) in temporary r0
// Ldar a2 // Load c
// Sub a0, [1] // c - a -> accumulator
// Mul r0, [2] // r0 * accumulator -> accumulator
// ReturnCommon Bytecode Instructions
// LOAD/STORE INSTRUCTIONS
// LdaSmi [n] - Load small integer n
// LdaConstant [idx] - Load from constant pool
// LdaZero - Load 0
// LdaTrue/LdaFalse - Load boolean
// LdaUndefined - Load undefined
// LdaNull - Load null
// Ldar rN - Load register into accumulator
// Star rN - Store accumulator into register
// ARITHMETIC
// Add rx, [slot] - accumulator + rx
// Sub rx, [slot] - accumulator - rx
// Mul rx, [slot] - accumulator * rx
// Div rx, [slot] - accumulator / rx
// Mod rx, [slot] - accumulator % rx
// AddSmi [n], [slot] - accumulator + small integer n
// MulSmi [n], [slot] - accumulator * small integer n
// Inc [slot] - accumulator++
// Dec [slot] - accumulator--
// COMPARISON
// TestEqual rx, [slot] - accumulator == rx
// TestStrictEqual rx, [slot] - accumulator === rx
// TestLessThan rx, [slot] - accumulator < rx
// TestGreaterThan rx, [slot] - accumulator > rx
// CONTROL FLOW
// Jump [offset] - Unconditional jump
// JumpIfTrue [offset] - Jump if accumulator is true
// JumpIfFalse [offset] - Jump if accumulator is false
// JumpIfToBooleanTrue - Jump if ToBoolean(accumulator) is true
// JumpLoop [offset], [osr] - Jump backward (loop), OSR counter
// OBJECT/PROPERTY ACCESS
// LdaNamedProperty obj, [name], [slot] - Load obj.name
// StaNamedProperty obj, [name], [slot] - Store to obj.name
// LdaKeyedProperty obj, [slot] - Load obj[key]
// StaKeyedProperty obj, key, [slot] - Store obj[key]
// FUNCTION CALLS
// CallProperty rx, [args...], [slot] - Call rx.method(args)
// CallUndefinedReceiver rx, [args] - Call function(args)
// Construct rx, [args], [slot] - new Constructor(args)
// Demonstrate with a real function
function processItem(item) {
if (item.active) {
item.count++;
return item.name.toUpperCase();
}
return null;
}
// Bytecode (simplified):
// LdaNamedProperty a0, "active", [0] // item.active
// JumpIfToBooleanFalse [end] // if (!item.active) goto end
// LdaNamedProperty a0, "count", [1] // item.count
// Inc [2] // ++
// StaNamedProperty a0, "count", [3] // item.count = result
// LdaNamedProperty a0, "name", [4] // item.name
// LdaNamedProperty <acc>, "toUpperCase", [5] // .toUpperCase
// CallProperty0 <acc>, [6] // ()
// Return
// end:
// LdaNull // null
// ReturnConstant Pool
// Large constants (strings, numbers > Smi range, regex) are stored
// in a per-function constant pool and referenced by index
function greeting(name) {
const prefix = "Hello, ";
const suffix = "! Welcome to the application.";
return prefix + name + suffix;
}
// Constant Pool:
// [0]: "Hello, "
// [1]: "! Welcome to the application."
//
// Bytecode:
// LdaConstant [0] // Load "Hello, " from constant pool index 0
// Star0 // Store in r0
// Ldar r0 // Load r0 (prefix)
// Add a0, [0] // prefix + name
// Star1 // Store intermediate result
// LdaConstant [1] // Load suffix from pool index 1
// Add r1, [1] // intermediate + suffix
// Return
// Numbers beyond Smi range also go to the constant pool
function bigNumber() {
return 9007199254740991; // MAX_SAFE_INTEGER
}
// Constant Pool:
// [0]: 9007199254740991 (HeapNumber)
//
// Bytecode:
// LdaConstant [0] // Load from constant pool (not LdaSmi)
// Return
// Small integers use LdaSmi (no constant pool entry)
function smallNumber() {
return 42;
}
// Bytecode:
// LdaSmi [42] // Inline in the instruction (no pool lookup)
// Return
// CONSTANT POOL SHARING
// V8 deduplicates constant pool entries within a function
function repeated() {
const a = "hello";
const b = "hello";
const c = "hello";
return a + b + c;
}
// Constant Pool has only ONE entry for "hello":
// [0]: "hello"
// All three loads reference index [0]Feedback Vectors
// Each feedback slot collects runtime type information
// This data guides TurboFan optimization decisions
function compute(a, b) {
const sum = a + b; // Feedback slot [0]: tracks types of a, b
const diff = a - b; // Feedback slot [1]: tracks types of a, b
return sum * diff; // Feedback slot [2]: tracks types of sum, diff
}
// After calling with numbers:
compute(10, 3);
// Slot [0]: BinaryOp_Add(Smi, Smi) -> Smi
// Slot [1]: BinaryOp_Sub(Smi, Smi) -> Smi
// Slot [2]: BinaryOp_Mul(Smi, Smi) -> Smi
// TurboFan sees all slots are Smi -> generates integer-only code
// After calling with a float:
compute(1.5, 2.7);
// Slot [0]: BinaryOp_Add(Smi|Number, Smi|Number) -> Number
// Slots transition to polymorphic type feedback
// PROPERTY ACCESS FEEDBACK
function getInfo(obj) {
return obj.name; // Feedback slot [0]: LoadIC
}
getInfo({ name: "A", age: 1 });
// Slot [0]: LoadIC(Map1, offset=0) -> Monomorphic
getInfo({ name: "B", role: "x" });
// Slot [0]: LoadIC(Map1|Map2) -> Polymorphic
// CALL FEEDBACK
function invoke(fn) {
return fn(42); // Feedback slot [0]: CallIC
}
invoke(Math.sqrt);
// Slot [0]: CallIC(Math.sqrt) -> Monomorphic
// TurboFan can replace with a direct CPU sqrt instruction
invoke(Math.abs);
// Slot [0]: CallIC(Math.sqrt|Math.abs) -> Polymorphic
// Viewing feedback in Node.js:
// node --trace-feedback-updates script.js
// Shows real-time feedback slot updates
// TYPEOF FEEDBACK
function checkType(x) {
if (typeof x === "string") { // Feedback slot: CompareOp
return x.length;
}
return 0;
}
// Slot records which type(s) 'x' has been
// TurboFan uses this to eliminate the typeof check for stable typesReading Bytecode Output
// How to interpret node --print-bytecode output
// Example function:
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Run: node --print-bytecode --print-bytecode-filter=fibonacci fib.js
// Output (annotated):
//
// [generated bytecode for function: fibonacci (0x...)]
// Bytecode length: 46
// Parameter count 2 <- 'this' + n = 2 parameters
// Register count 2 <- r0, r1 used for temporaries
// Frame size 16 <- 2 registers * 8 bytes
//
// 0: LdaSmi [1] // Load 1
// 2: TestLessThanOrEqual a0, [0] // n <= 1 ?
// 5: JumpIfFalse [4] // Jump to offset 9 if false
// 7: Ldar a0 // Load n
// 9: Return // Return n (base case)
//
// 10: LdaGlobal [0], [1] // Load 'fibonacci' function
// 13: Star1 // Store in r1
// 14: Ldar a0 // Load n
// 16: SubSmi [1], [3] // n - 1
// 19: Star0 // Store n-1 in r0
// 20: CallUndefinedReceiver1 r1, r0, [4] // fibonacci(n-1)
// 23: Star0 // Store result in r0
// 24: LdaGlobal [0], [1] // Load 'fibonacci' again
// 27: Star1 // Store in r1
// 28: Ldar a0 // Load n
// 30: SubSmi [2], [6] // n - 2
// 33: Star<temp> // Store n-2
// 34: CallUndefinedReceiver1 r1, <temp>, [7] // fibonacci(n-2)
// 37: Add r0, [9] // fibonacci(n-1) + fibonacci(n-2)
// 40: Return // Return sum
//
// Constant pool:
// 0: "fibonacci" // Function name for global lookup
//
// Handler table: // Exception handlers (empty here)| Instruction Category | Example | Byte Size | Description |
|---|---|---|---|
| Load immediate | LdaSmi [42] | 2-3 bytes | Load constant into accumulator |
| Load register | Ldar r0 | 2 bytes | Copy register to accumulator |
| Store register | Star0 | 1 byte | Copy accumulator to register |
| Binary operation | Add r1, [slot] | 3 bytes | Arithmetic with feedback |
| Property access | LdaNamedProperty | 4 bytes | Object property load |
| Jump | JumpIfFalse [off] | 3 bytes | Conditional branch |
| Call | CallProperty | 4+ bytes | Function/method call |
Rune AI
Key Insights
- V8 bytecode uses a register-based format with an implicit accumulator register: Most operations read from or write to the accumulator, with named registers for locals and temporaries
- Feedback slots attached to bytecode instructions collect runtime type information: Every arithmetic, property access, and call instruction profiles the types it observes for TurboFan
- The constant pool stores strings, large numbers, and other values referenced by index: Small integers use inline LdaSmi instructions, while larger constants require pool lookups
- Context slots replace registers for variables captured by closures: Closure-captured variables live on the heap in Context objects, making them slower to access than register locals
- Bytecode compiles in a single pass and is 5-10x more compact than machine code: This fast generation enables quick startup while keeping memory usage low for cold functions
Frequently Asked Questions
Why does V8 use bytecode instead of compiling directly to machine code?
How do feedback vectors affect optimization?
Can I control which bytecodes V8 generates?
What is the relationship between bytecode size and performance?
Conclusion
V8 bytecode is the bridge between JavaScript source code and machine execution. Understanding the register-based instruction set, constant pool management, and feedback vectors reveals how the engine executes your code. Each bytecode instruction maps to a specific JavaScript operation. Feedback slots drive optimizing compilation. For how bytecode becomes optimized machine code, see JavaScript JIT Compilation: Advanced Tutorial. For the Ignition interpreter that executes this bytecode, review Ignition Interpreter and JS Bytecode Tutorial.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.