Course contentsShow
← Web Development
Lesson 2108 of 2,98238. JavaScript Performance in the BrowserFree lesson

How JavaScript Garbage Collection Works

Learn the basics of garbage collection, reachability, and when the browser can reclaim memory.

How JavaScript Garbage Collection Works

You'll learn how browsers automatically reclaim unused memory and when objects become eligible for cleanup.

What is Garbage Collection?

JavaScript doesn't require you to manually free memory like lower-level languages. Instead, the browser's garbage collector (GC) automatically identifies and removes objects you're no longer using. Think of it like a cleaning service that periodically comes through your workspace and throws away trash you've left behind—but it has to figure out what counts as "trash."

The Core Concept: Reachability

The fundamental principle is reachability. An object is considered "reachable" if your code can still access it somehow. The garbage collector keeps everything reachable and deletes everything else.

Starting from roots (global variables, currently executing functions, the call stack), the GC traces all references. If an object can't be reached by following any chain of references from a root, it's garbage.

let user = { name: "Alice" }; // Reachable from 'user' variable
user = null; // The object is now unreachable → eligible for GC

function createData() {
  let temp = { data: new Array(1000) }; // Reachable while function runs
  return temp.data;
}
const result = createData(); // 'temp' object unreachable after function ends

When Memory is Reclaimed

The browser runs garbage collection automatically, typically during idle time or when memory pressure increases. You can't force it or predict exactly when it happens. This is why memory leaks occur—objects you think are "done" remain reachable through forgotten references.

Key Takeaway: JavaScript's garbage collector automatically frees memory for objects that are no longer reachable from your code's roots; understanding reachability helps you avoid accidentally keeping objects alive longer than needed.