How does garbage collection work in JavaScript?
Understand how JavaScript automatically frees memory using reachability and reference checks.
Question
How does garbage collection work in JavaScript?
Answer
JavaScript has automatic garbage collection.
It uses a reachability model — if an object is no longer reachable from the root (like window or the global scope), it becomes garbage and is eligible for cleanup.
let user = { name: 'Ghazi' };
user = null; // object is no longer referenced → can be collected
Modern JS engines (V8, SpiderMonkey) use mark-and-sweep:
- Start from roots
- Mark all reachable objects
- Sweep unmarked ones
Real-World Example
Memory leaks often happen when we keep references in:
- global variables
- long-lived closures
- DOM elements not removed from code
Quick Practice
Create an object, reference it in an array, then remove all references and explain when it becomes collectible.
Summary
GC in JS is automatic but not magic — your job is to avoid holding unnecessary references.
Can I manually force garbage collection?
In browsers, no. JavaScript engines decide when to collect. In Node, there is a debug flag, but you shouldn’t rely on it.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.