How JavaScript Stores Primitive Values in Memory
Learn how JavaScript stores primitive values on the stack and objects on the heap. Understand stack vs heap memory, garbage collection, and how memory allocation affects your code's performance.
Understanding how JavaScript manages memory is one of those skills that separates developers who write code from developers who understand why their code behaves the way it does. When you declare a variable, JavaScript allocates memory for that value. Where and how it stores that value depends entirely on whether it is a primitive or a reference type. This article focuses on primitive values: how they land on the stack, why they behave as independent copies, and how the engine manages their lifecycle.
If you are still building your understanding of JavaScript data types, review that guide first. This article dives one level deeper into what happens behind the scenes when you work with those types.
The Two Memory Areas: Stack and Heap
JavaScript engines (like V8 in Chrome and Node.js) use two primary memory regions to store data:
| Memory Region | What Gets Stored | Access Speed | Size | Lifecycle |
|---|---|---|---|---|
| Stack | Primitive values, function call frames, local variable references | Very fast (LIFO) | Small, fixed | Automatic (scope-based) |
| Heap | Objects, arrays, functions, closures | Slower (random access) | Large, dynamic | Garbage collected |
The stack is a simple, fast, last-in-first-out (LIFO) data structure. Every time a function is called, a new "frame" is pushed onto the stack containing the function's local variables. When the function returns, that frame is popped off.
The heap is a larger, unstructured memory pool where objects live. Accessing heap memory is slower because the engine must follow a reference (pointer) to find the data.
How Primitives Are Stored on the Stack
When you declare a primitive variable, the value is stored directly in the variable's stack frame slot. There is no indirection, no pointer, no separate memory location.
function calculateTotal() {
const itemPrice = 29.99; // 29.99 stored directly on the stack
const quantity = 3; // 3 stored directly on the stack
const taxRate = 0.08; // 0.08 stored directly on the stack
const total = itemPrice * quantity * (1 + taxRate);
return total; // total value is returned, frame is popped
}During execution, the stack looks conceptually like this:
STACK (grows downward)
┌──────────────────────────┐
│ calculateTotal() frame │
│ ├── itemPrice: 29.99 │
│ ├── quantity: 3 │
│ ├── taxRate: 0.08 │
│ └── total: 97.1676 │
├──────────────────────────┤
│ global frame │
│ └── (global variables) │
└──────────────────────────┘
When calculateTotal() finishes, its entire stack frame is removed. The memory for itemPrice, quantity, taxRate, and total is reclaimed instantly. No garbage collector is needed.
Why Primitives Copy by Value
Because primitives live directly on the stack, copying a primitive means copying the actual value into a new stack slot. The two variables are completely independent.
let temperature = 72;
let savedTemperature = temperature; // Copies the value 72 to a new stack slot
temperature = 85;
console.log(temperature); // 85
console.log(savedTemperature); // 72 (completely independent)The stack during this operation:
Before reassignment: After reassignment:
┌──────────────────────┐ ┌──────────────────────┐
│ temperature: 72 │ │ temperature: 85 │
│ savedTemperature: 72 │ │ savedTemperature: 72 │
└──────────────────────┘ └──────────────────────┘
Each variable gets its own copy of the number 72. Changing temperature creates a new value 85 in that slot without touching savedTemperature.
How Objects Differ: The Heap Connection
Objects are stored differently. The stack holds a reference (memory address) pointing to the object on the heap. This is why primitive vs reference types behave so differently when copied.
const user = { name: "Ada", age: 25 };
const userRef = user;The memory layout:
STACK HEAP
┌──────────────────────┐ ┌──────────────────────┐
│ user: ──────────────────────►│ { name: "Ada", │
│ userRef: ───────────────────►│ age: 25 } │
└──────────────────────┘ └──────────────────────┘
Both user and userRef hold the same pointer on the stack. They point to a single object on the heap. This is why modifying userRef.age = 30 also changes user.age.
Primitive Immutability and Memory
Primitives are immutable. You cannot change the value 42 or the string "hello" in memory. When you "modify" a primitive, JavaScript creates a new value and points the variable at it.
let greeting = "hello";
greeting = greeting.toUpperCase();
// "hello" still exists in memory (until garbage collected)
// "HELLO" is created as a new string
// greeting now points to "HELLO"String Internalization
JavaScript engines optimize string storage through a process called "interning." When multiple variables hold the same string value, the engine may store only one copy and point all variables to it. This is an internal optimization; from your code's perspective, strings still behave as independent values.
Numbers and Memory Precision
The Number type in JavaScript uses 64-bit IEEE 754 floating-point format. Every number occupies exactly 8 bytes of memory on the stack, whether it is 0, 42, 3.14159, or Number.MAX_SAFE_INTEGER.
const zero = 0; // 8 bytes
const pi = 3.141592653589793; // 8 bytes
const maxSafe = 9007199254740991; // 8 bytes
const tiny = 0.000000001; // 8 bytes| Data Type | Memory Size per Value | Storage Location |
|---|---|---|
| Number | 8 bytes (64-bit float) | Stack |
| Boolean | 1 byte (engine-dependent) | Stack |
| Null | 0 bytes (tag only) | Stack |
| Undefined | 0 bytes (tag only) | Stack |
| BigInt | Variable (depends on magnitude) | Heap (due to arbitrary size) |
| Symbol | Reference to internal table | Stack (reference) + Heap (description) |
| String | Variable (depends on length) | Stack (short) or Heap (long) |
Small Strings vs Large Strings
Short strings (roughly 10 characters or fewer, engine-dependent) are often stored directly on the stack for performance. Longer strings are allocated on the heap, with a reference on the stack.
const short = "hi"; // Likely stored inline on the stack
const long = "a".repeat(1000); // Stored on the heap, reference on stackThis is an engine optimization detail. From your code's perspective, all strings behave identically regardless of where they are physically stored.
Function Calls and the Stack
Each function call creates a new stack frame. Primitive arguments are copied into the new frame, which is why modifying a parameter inside a function does not affect the caller's variable.
function applyDiscount(price, discountPercent) {
// 'price' and 'discountPercent' are copies in this frame
price = price * (1 - discountPercent / 100);
return price;
}
const originalPrice = 100;
const finalPrice = applyDiscount(originalPrice, 20);
console.log(originalPrice); // 100 (untouched)
console.log(finalPrice); // 80 (new value returned)The stack during the call:
STACK (during applyDiscount execution)
┌──────────────────────────────┐
│ applyDiscount() frame │
│ ├── price: 100 → 80 │
│ └── discountPercent: 20 │
├──────────────────────────────┤
│ global frame │
│ ├── originalPrice: 100 │
│ └── finalPrice: (pending) │
└──────────────────────────────┘
When applyDiscount returns, its frame is popped. The price and discountPercent copies disappear. Only the returned value survives.
Garbage Collection for Primitives
Stack-based primitives are automatically deallocated when their scope ends. The garbage collector primarily handles heap memory (objects). However, some primitives (large strings, BigInts) that live on the heap are garbage collected like objects.
function processOrder() {
const orderId = "ORD-12345"; // Stack allocated
const description = "A".repeat(5000); // Heap allocated (large string)
// Both are accessible within this function
return orderId;
}
// After processOrder() returns:
// - orderId's stack slot is gone (frame popped)
// - description's heap memory is eligible for garbage collection
// - The returned orderId value is copied to the caller's frameMemory Leaks with Closures
Closures can keep primitive values alive longer than expected. If an inner function captures a variable from an outer scope, the engine cannot deallocate that variable's memory until the inner function itself is garbage collected, even if the outer function has returned.
function createCounter() {
let count = 0; // This primitive stays alive as long as the returned function exists
return function increment() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
// 'count' is NOT garbage collected because 'counter' still references itBest Practices
Memory-Conscious Coding
These practices help you write JavaScript that uses memory efficiently.
Use const for primitives that do not change. const signals to the engine and to other developers that this binding is stable. Some engines may optimize const declarations differently in hot code paths.
Avoid creating unnecessary intermediate strings. String operations like repeated concatenation in a loop create a new string object for each iteration. Use Array.join() instead for building large strings.
// Wasteful: creates a new string every iteration
let result = "";
for (let i = 0; i < 10000; i++) {
result += "item " + i + ", ";
}
// Better: join an array once
const parts = [];
for (let i = 0; i < 10000; i++) {
parts.push(`item ${i}`);
}
const result2 = parts.join(", ");Limit closure scope to what you need. If a closure only needs one variable from the outer scope, restructure your code so only that variable is captured, not the entire scope.
Be mindful of BigInt for large number operations. BigInt values are heap-allocated and more expensive than regular numbers. Use them only when you actually need integers beyond Number.MAX_SAFE_INTEGER.
Common Mistakes and How to Avoid Them
Memory Pitfalls
These mistakes affect performance and can lead to subtle memory-related bugs.
Thinking all data lives on the stack. Only primitive values and references live on the stack. The objects those references point to live on the heap. This distinction is crucial for understanding copy behavior and memory lifetime.
Building large strings with += in loops. Each concatenation creates a new string, and the old string becomes garbage. In a loop with thousands of iterations, this creates thousands of temporary strings the garbage collector must clean up.
Keeping closures alive unnecessarily. A closure captures its entire outer scope. If the outer function has large variables you do not need, the closure keeps them in memory. Set unused variables to null or restructure to minimize captured scope.
Assuming primitive operations are always free. While stack operations are fast, operations that create new primitives (like string manipulation) still cost memory allocation time. In performance-critical code, be aware of how many new values you create per frame.
Next Steps
Master [type conversion](/tutorials/programming-languages/javascript/javascript-type-conversion-coercion-explained)
Learn how JavaScript converts between types during operations and how each conversion affects the values stored in memory.
Explore closures and scope
Understand how closures capture variables from outer scopes and what this means for memory lifetime in the functions tutorial.
Learn about garbage collection
Dive deeper into how V8's garbage collector works, including generational collection and mark-and-sweep algorithms.
Profile memory in [Chrome DevTools](/tutorials/programming-languages/javascript/how-to-execute-javascript-in-chrome-devtools)
Use Chrome's Memory panel to take heap snapshots, track allocations, and find memory leaks in real applications.
Rune AI
Key Insights
- Primitives live on the stack: stored directly in the variable's memory slot for fast access
- Copying is independent: assigning a primitive to a new variable creates a separate copy of the value
- Stack cleanup is automatic: when a function returns, all its local primitive values are instantly deallocated
- Large strings and BigInts use the heap: not all "primitives" are stack-allocated; size determines placement
- Closures extend memory lifetime: captured variables remain in memory until the closure itself is garbage collected
Frequently Asked Questions
Does JavaScript store all primitives on the stack?
How much memory does a JavaScript number use?
What happens to stack memory when a function returns?
Can primitives cause memory leaks in JavaScript?
Why are primitive operations faster than object operations?
Conclusion
JavaScript stores primitive values directly on the stack for fast, automatic memory management. When you copy a primitive, the engine duplicates the actual value into a new stack slot, creating complete independence between variables. Stack memory is automatically reclaimed when functions return, making primitives cheap and efficient. Understanding this mechanism explains why primitives copy by value, why function parameters do not affect their callers, and why closures can extend a value's lifetime beyond its original scope.
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.