Sub topic 2
Stack, Heap, and Values vs References
This chapter assumes you know JavaScript variables, objects, arrays, and functions, and that you can run code in a browser console or Node.js. It builds on the allocate-use-release lifecycle from the previous chapter. Here you will see where allocated data lives and what a variable actually holds.
Two Regions of Memory
Engines such as V8 organize memory into two broad regions.
| Region | What it holds | Lifetime | Managed by |
|---|---|---|---|
| Stack | Call frames: local variables, arguments, return addresses | Ends when the function returns | Push and pop, automatically |
| Heap | Objects, arrays, functions, closures, most strings | Until no longer reachable | The garbage collector |
The stack is a last-in, first-out structure. Each function call pushes a frame, and returning pops it. Freeing stack memory costs almost nothing, so the garbage collector never has to deal with it.
The heap is a large pool for data whose size or lifetime can't be known when the function is entered. An object created inside a function can outlive that function if something returns or stores it. That is why heap memory needs a collector.
Primitives and References
JavaScript has seven primitive types: number, string, boolean, undefined, null, bigint, and symbol. Everything else is an object.
- A variable holding a primitive acts as if it holds the value itself.
- A variable holding an object holds a reference, which works like an address pointing to the object on the heap.
Assignment copies whatever the variable holds. With a primitive, you get an independent value. With an object, you get a second reference to the same object.
let a = 10;
let b = a; // copies the value
b = 20;
console.log(a); // 10
const p = { x: 1 };
const q = p; // copies the reference, not the object
q.x = 99;
console.log(p.x); // 99, because p and q point to one objectPassing Arguments: "By Sharing"
JavaScript always passes arguments by value. When the argument is an object, the value being copied is the reference. This is often called call by sharing. A function can therefore mutate the caller's object, but reassigning the parameter has no effect on the caller.
function mutate(obj) {
obj.count = 1; // changes the shared object
}
function reassign(obj) {
obj = { count: 2 }; // rebinds the local parameter only
}
const data = { count: 0 };
mutate(data);
console.log(data.count); // 1
reassign(data);
console.log(data.count); // still 1Common Errors
- Assuming
=clones.const copy = originalproduces an alias, not a copy. Use{ ...original }orstructuredClone(original)when you need an independent object. - Shallow copies hide shared nested objects. Spread copies only the top level, so nested objects are still shared.
- Confusing
constwith immutability.conststops you from rebinding the variable. The object it refers to can still be changed. - Comparing objects with
===. This compares references, so two objects with identical contents are not equal.
const original = { tags: ["a"] };
const shallow = { ...original };
shallow.tags.push("b");
console.log(original.tags); // ["a", "b"], the array is shared
const deep = structuredClone(original);
deep.tags.push("c");
console.log(original.tags); // ["a", "b"], unaffectedWhy This Matters for Memory
When a stack frame is popped, its local references disappear, but the heap objects they pointed to stay where they are. Each of those objects stays in memory for as long as some other reference still leads to it. Every alias you create, whether through assignment, a function argument, or a property on another object, is one more path that can keep a heap object alive. The next chapter defines those paths precisely as reachability.
Exercise
After running let s = "hi"; let t = s; t += "!"; const o = { v: [1] }; const r = { ...o }; r.v = [2];, what are s and o.v, and why?
Show answer
s is "hi" because strings are immutable primitives, so t += "!" makes a new string and binds it to t. o.v is [1] because r.v = [2] replaces the property on the shallow copy r and doesn't change the array the two objects originally shared.
Exercise
A function receives an object parameter and sets it to null on its first line. Does this free the caller's object?
Show answer
No. Setting the parameter to null only clears the function's local copy of the reference. The caller's variable still references the object, so the object stays reachable.