Course contentsShow
← JavaScript
Lesson 1861 of 2,72339. Memory Management and GCFree lesson

Reachability: The Core Concept

How the GC determines which objects are still in use by tracing from root references like global variables.

Reachability: The Core Concept

What you'll learn: How JavaScript's garbage collector decides which objects to keep and which to delete by tracing connections from "roots."

The Core Idea

Garbage collection works by tracking reachability—whether a value can still be accessed from your running code. The GC starts from special starting points called roots (like global variables, currently executing functions, and their local variables) and traces all references outward. Any object the GC can reach by following these reference chains is considered "alive" and kept in memory. Everything else is unreachable garbage that gets cleaned up.

How the Trace Works

Think of reachability like a spider following its web. The spider (garbage collector) starts at the center (roots) and crawls along every strand (reference). Any fly (object) it can reach this way is "reachable." Flies on broken strands that can't be reached? Those get removed.

Roots include:

  • Global variables (window in browsers, global in Node.js)
  • Local variables in currently executing functions
  • Variables in the call stack

A Mental Model

let user = { name: "Alice" };  // user is a root → object is reachable

let admin = user;  // Two references to same object → still reachable

user = null;  // One reference gone, but admin still holds it → reachable

admin = null;  // No references left → UNREACHABLE → eligible for GC

Once an object has no path back to any root, it becomes "garbage." The GC will eventually reclaim its memory.

Key Takeaway: The garbage collector keeps objects alive by tracing references from roots—if there's no path from a root to an object, that object is unreachable and will be collected.