Sub topic 1
How JavaScript Allocates and Releases Memory
Prerequisites
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 also assumes a basic grasp of scope.
The Memory Lifecycle
Every value goes through three steps: allocate, use, and release. JavaScript allocates memory for you whenever you create a value, and you use it by reading and writing that value. You never free memory yourself. The engine's garbage collector (GC) releases memory once it can prove the value is no longer needed. The common mistake is to think that setting a variable to null frees memory. It only removes one reference to the value.
Stack, Heap, and Values vs References
Engines keep short-lived, fixed-size data, such as call frames and many primitives, on the stack. Objects, arrays, and functions live on the heap, and variables hold references to them. When you copy a primitive, you copy its value. When you copy an object variable, you copy the reference, so both variables point at the same heap object.
Reachability
The GC keeps any value it can reach from a root. Roots include the global object, the variables of the functions currently running, and the call stack. A value stays alive while some chain of references from a root leads to it.
let user = { name: "Ada" };
let admin = user;
user = null; // the object is still reachable through admin
admin = null; // now unreachable and eligible for collectionReference Counting and Cycles
Early engines counted the references to each object and freed an object when its count reached zero. That approach fails on cycles:
function makeCycle() {
const a = {};
const b = {};
a.other = b;
b.other = a;
}
makeCycle();After makeCycle returns, a and b still reference each other. Each count stays at 1, so a reference-counting collector never frees them.
Mark-and-Sweep
Modern engines use mark-and-sweep. The mark phase starts at the roots and flags every object it can reach. The sweep phase then frees everything left unmarked. In the example above, no root reaches the a/b cycle, so both objects are freed.
Exercise
After running let a = { v: 1 }; let b = a; a = null;, can the object { v: 1 } be collected? Explain your answer using reachability.
Show answer
No. The variable b is a root reference that still points to the object, so the object stays reachable. Once b is also set to null or goes out of scope, the object becomes unreachable and can be collected.
Exercise
Why does a mark-and-sweep collector free two objects that reference each other when a reference-counting collector does not?
Show answer
Under reference counting, each object in the cycle keeps the other's count at 1, so neither count reaches zero. Mark-and-sweep only marks objects it can reach from roots. No root reaches the cycle, so both objects stay unmarked and are swept.