Sub topic 2
Stack, Heap, and Values vs References
The garbage collector works on objects, so before you can reason about it you need to know which values are objects and how variables refer to them. This chapter builds that model. It covers what the stack and the heap are, how primitives differ from objects when you assign or pass them, and where the simple "primitives on the stack, objects on the heap" story stops being accurate.
This chapter assumes you can write JavaScript functions, objects, and arrays, and that you can run snippets in Node.js or a browser console. It builds on the previous chapter's allocate-use-release lifecycle.
Two regions of memory
Engines such as V8, SpiderMonkey, and JavaScriptCore manage memory in two broad regions.
The stack is a region that holds one frame per active function call. A frame holds the call's local bookkeeping: arguments, local variables, and the return address. When a function is called, the engine pushes a frame. When the function returns, the engine pops it. Stack memory is freed by that pop, so no garbage collector is involved and the cost is close to zero.
The heap is a large pool for values whose lifetime is not tied to a single call. Objects, arrays, functions, maps, and closures' captured scopes live here. A heap value can outlive the call that created it, so the engine cannot free it on return. Deciding when heap memory can be released is the garbage collector's whole job.
| Property | Stack | Heap |
|---|---|---|
| Lifetime | Ends when the function returns | Ends when the value becomes unreachable |
| Freed by | Popping the frame | The garbage collector |
| Size | Small and fixed (often around 1 MB) | Large, grows on demand up to a limit |
| Allocation cost | A pointer bump | Higher, and creates future GC work |
| Typical contents | Frames, small values, pointers | Objects, arrays, functions, strings |
Primitives and objects
JavaScript has seven primitive types: undefined, null, boolean, number, bigint, string, and symbol. Everything else is an object, and that includes arrays, functions, dates, and regular expressions.
The difference that matters here is mutability. A primitive can never be changed in place. "abc".toUpperCase() returns a new string and leaves the original untouched. An object can be changed in place, and every variable that refers to it sees the change.
A variable that holds an object does not contain the object. It contains a reference, which is the address of the object on the heap.
Assignment copies the value in the variable
Assignment always copies whatever is stored in the variable. For a primitive, that is the value itself. For an object, it is the reference, so after the copy both variables point at the same heap object.
let a = 10;
let b = a; // copies the number
b = 20;
console.log(a, b); // 10 20
const user = { name: "Ada" };
const admin = user; // copies the reference, not the object
admin.name = "Grace";
console.log(user.name); // "Grace"
console.log(user === admin); // true: same object
const other = { name: "Grace" };
console.log(user === other); // false: equal contents, different objects=== on objects compares references, not contents. Two object literals with identical fields are still two separate heap allocations.
Passing arguments: call by sharing
JavaScript passes every argument by value. When the argument is an object, the value being copied is a reference. This is often called call by sharing. The function can mutate the shared object, but reassigning the parameter only changes the local copy of the reference.
function rename(person) {
person.name = "Linus"; // mutates the shared object
}
function replace(person) {
person = { name: "Margaret" }; // rebinds the local parameter only
}
const p = { name: "Ada" };
rename(p);
console.log(p.name); // "Linus"
replace(p);
console.log(p.name); // still "Linus"This is the reason a reference stored anywhere (an array, a cache, a closure, an event registry) keeps the object alive. Passing an object to a function that stores it creates a new path to that object. The next chapter turns this into the rule the collector actually uses.
`const` freezes the binding, not the object
A common error is to assume const makes an object immutable. const stops you from reassigning the variable. The heap object it points to is still mutable.
const config = { retries: 3 };
config.retries = 5; // allowed
console.log(config.retries); // 5
try {
config = {}; // TypeError: Assignment to constant variable.
} catch (err) {
console.log(err.name); // "TypeError"
}
const frozen = Object.freeze({ retries: 3 });
frozen.retries = 10; // silently ignored (throws in strict mode)
console.log(frozen.retries); // 3Object.freeze is shallow. Nested objects inside a frozen object can still be changed.
Copying objects: shallow and deep
Because assignment shares references, you have to ask for a copy explicitly. Spread syntax and Object.assign make a shallow copy. They create a new top-level object, but nested objects are still shared. structuredClone makes a deep copy of plain data.
const original = { id: 1, tags: ["a", "b"] };
const shallow = { ...original };
shallow.tags.push("c");
console.log(original.tags); // ["a", "b", "c"]: nested array is shared
const deep = structuredClone(original);
deep.tags.push("d");
console.log(original.tags); // ["a", "b", "c"]: unaffected
console.log(deep.tags); // ["a", "b", "c", "d"]Every copy is a new heap allocation. A deep clone of a large structure allocates every nested object again, which costs memory and creates work for the collector. structuredClone also throws a DataCloneError on functions and DOM nodes, and it does not preserve class prototypes.
Where the simple model breaks
"Primitives on the stack, objects on the heap" is a useful first approximation. In real engines it is wrong in several ways, and these are the cases that cause confusion when you read heap snapshots.
Strings live on the heap
Strings can be megabytes long, so they cannot fit in a stack slot. V8 allocates strings on the heap and stores a reference in the variable. They still behave like values because they are immutable: nobody can change a string through a shared reference, so sharing is invisible. This is why heap snapshots show large (string) entries even though typeof reports a primitive.
V8 also uses internal representations such as concatenated strings and sliced strings, which point into other strings. A short slice of a huge string can keep the whole parent string alive.
let huge = "x".repeat(10_000_000);
let piece = huge.slice(0, 10); // may internally reference huge
huge = null;
// Depending on the engine, piece can retain the 10 MB parent.
// Forcing a flat copy breaks that link in practice:
piece = [...piece].join("");
console.log(piece.length); // 10Numbers are sometimes boxed
V8 stores small integers, called Smis (small integers), directly inside the tagged value with no allocation. Other numbers, such as 0.5 or integers outside the Smi range, may be stored as a heap object called a HeapNumber. Optimized code often keeps doubles unboxed in registers or object fields, so whether a number allocates depends on how hot and how stable the code is. BigInts are always heap allocated.
Captured variables move to the heap
A local variable normally lives in the stack frame or in a CPU register. If an inner function captures it, the variable must survive after the outer call returns. V8 moves such variables into a heap-allocated context object that the closure references. Chapter 6 covers what that means for retained memory.
Objects might never reach the heap
The optimizing compiler can perform escape analysis. If it proves an object never leaves a function, it can replace the object with its fields held in registers and skip the allocation entirely. You cannot control this directly, but it means short-lived objects in hot loops are sometimes free.
| Value | Common placement in V8 | Behaves as |
|---|---|---|
| Small integer (Smi) | Inline in the tagged value | Value |
| Double, large integer | Heap `HeapNumber`, or unboxed when optimized | Value |
| BigInt | Heap | Value |
| String | Heap | Value (immutable) |
| Captured local | Heap context object | Shared binding |
| Object, array, function | Heap, or eliminated by escape analysis | Reference |
The stack has its own limit
The stack is small, so deep recursion exhausts it before it touches the heap. The error is a RangeError, not an out-of-memory crash, and it has nothing to do with garbage collection.
function depth(n) {
return depth(n + 1);
}
try {
depth(0);
} catch (err) {
console.log(err instanceof RangeError, err.message);
// true "Maximum call stack size exceeded"
}A heap out-of-memory failure is different. Node.js prints FATAL ERROR: ... JavaScript heap out of memory and the process terminates. Your code cannot catch it. Recognizing which of the two you hit tells you whether to look at recursion depth or at retained objects.
Common errors
- Assuming
constmakes data immutable, then mutating shared configuration from several modules. - Using a spread copy to "isolate" state and later mutating a nested array that is still shared.
- Comparing objects with
===and expecting a content comparison. - Reassigning a parameter inside a function and expecting the caller's variable to change.
- Treating every primitive as free of heap cost, when long strings and BigInts are heap allocations that show up in snapshots.
Exercise
After running const a = { list: [1, 2] }; const b = { ...a }; b.list = [9]; b.list.push(3); a.list.push(4);, what are a.list and b.list, and how many array objects exist on the heap?
Show answer
a.list is [1, 2, 4] and b.list is [9, 3]. The spread first shared the original array between both objects. Then b.list = [9] pointed b.list at a new array, so later pushes affect separate arrays. Two arrays exist: the original [1, 2, 4], referenced by a.list, and [9, 3], referenced by b.list.
Exercise
A function function reset(state) { state = { count: 0 }; } is called as reset(appState), but appState.count keeps its old value. Explain why, and give two ways to fix it.
Show answer
Arguments are passed by sharing. state holds a copy of the reference, and reassigning it only rebinds the local parameter, so the caller's object is untouched. One fix is to mutate the shared object (state.count = 0; or Object.assign(state, { count: 0 })). The other is to return a new object and reassign at the call site (appState = reset();), which requires appState to be declared with let.
Exercise
typeof s === "string" is true, yet a heap snapshot shows s accounting for 20 MB. How can a primitive occupy that much heap memory?
Show answer
Engines allocate string contents on the heap because strings can be arbitrarily long, and the variable holds a reference to them. Strings behave like values only because they are immutable. A small substring can also internally reference a much larger parent string, which keeps the parent's memory alive.