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.

JavaScriptadvanced
18 min read

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.

javascriptjavascript
// 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 code

Register Allocation

javascriptjavascript
// 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
//   Return

Common Bytecode Instructions

javascriptjavascript
// 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
//   Return

Constant Pool

javascriptjavascript
// 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

javascriptjavascript
// 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 types

Reading Bytecode Output

javascriptjavascript
// 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 CategoryExampleByte SizeDescription
Load immediateLdaSmi [42]2-3 bytesLoad constant into accumulator
Load registerLdar r02 bytesCopy register to accumulator
Store registerStar01 byteCopy accumulator to register
Binary operationAdd r1, [slot]3 bytesArithmetic with feedback
Property accessLdaNamedProperty4 bytesObject property load
JumpJumpIfFalse [off]3 bytesConditional branch
CallCallProperty4+ bytesFunction/method call
Rune AI

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
RunePowered by Rune AI

Frequently Asked Questions

Why does V8 use bytecode instead of compiling directly to machine code?

Bytecode provides a balance between startup speed and execution speed. Generating bytecode from the AST is fast (single pass, no optimization), so functions start executing quickly. Bytecode is also 5-10x more compact than machine code, reducing memory pressure. If a function runs hot, TurboFan compiles it to optimized machine code later. Most functions in an application run only a few times, so bytecode's fast generation saves more time than optimized machine code would gain.

How do feedback vectors affect optimization?

Feedback vectors are the bridge between the interpreter and the optimizing compiler. Every bytecode operation that depends on runtime types (arithmetic, property access, function calls) has a feedback slot that records observed types. When TurboFan compiles a hot function, it reads these slots to generate type-specialized machine code. Stable feedback (always seeing the same types) produces the fastest optimized code. Unstable feedback forces TurboFan to generate slower, more generic code.

Can I control which bytecodes V8 generates?

Not directly, but your coding patterns determine the bytecodes. Simple arithmetic generates Add/Mul bytecodes. Property access generates LdaNamedProperty. Function calls generate CallProperty or CallUndefinedReceiver. Using `const` vs `let` can eliminate some stores. Avoiding unnecessary temporary variables reduces register pressure. The key is writing straightforward code, which maps to efficient bytecodes naturally.

What is the relationship between bytecode size and performance?

Smaller bytecode functions execute faster in the interpreter because there are fewer instructions to dispatch. But bytecode size does not directly predict optimized performance since TurboFan may generate very different machine code. Bytecode size matters most for cold functions (called once or twice) that stay in the interpreter. For hot functions, TurboFan optimization quality matters more than bytecode size.

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.