Roots and Reference Chains
You'll learn how JavaScript identifies which objects must stay in memory and how reference chains determine what gets garbage collected.
What Are GC Roots?
Garbage collection roots are the starting points the engine uses to determine reachability. These are values that are always considered reachable and cannot be garbage collected:
- Global variables – Anything in the global scope (
windowin browsers,globalin Node.js) - Currently executing functions – Variables on the call stack
- Closures – Variables captured by inner functions still in memory
Think of roots as the top of a tree. The garbage collector "walks" down from these roots, following every reference like branches.
Reference Chains Keep Objects Alive
An object stays alive if there's an unbroken chain of references from any root to that object:
let globalUser = { name: "Alice" }; // Root: global variable
globalUser.profile = { age: 30 }; // profile reachable via globalUser
function createClosure() {
let localData = { id: 123 }; // Root: on call stack
return function() {
console.log(localData.id); // Root: captured in closure
};
}
let myFunc = createClosure(); // myFunc keeps localData alive
Even though localData is no longer on the stack after createClosure() returns, it's still reachable through the closure stored in myFunc (which is global). Break the chain, and the object becomes collectible:
myFunc = null; // localData now unreachable → eligible for GC
The Mark-and-Sweep Walk
The collector starts at roots and "marks" every object it can reach. Anything unmarked at the end has no reference chain back to a root and gets swept away.
Key Takeaway: Objects survive garbage collection only if there's a reference chain connecting them to a GC root—global scope, active call stack, or living closure.