Garbage collection (GC) in JavaScript is an automatic memory management process that frees up memory by removing objects that are no longer reachable (i.e., no longer used by the program).
You don’t manually allocate or deallocate memory — the JavaScript engine does it for you.
1️⃣ The Concept of Reachability
An object is reachable if it can be accessed directly or indirectly from the program’s “root.”
Roots include:
- Global variables
- Local variables in current functions
- Variables in the call stack
If an object is not reachable, it’s considered garbage and is removed from memory.
Example:
let user = { name: "Teekam" }; // Object is reachable via 'user'
user = null; // No references → becomes unreachable → garbage collected
2️⃣ The Mark-and-Sweep Algorithm (Most Common)
This is how most modern JS engines (like V8 in Chrome) handle garbage collection.
Steps:
- Mark: The garbage collector marks all reachable objects starting from the roots.
- Sweep: It removes (frees) all objects not marked as reachable.
Illustration:
Roots → { Global Variables } → Reachable Objects
⮑ Unreachable objects = collected (deleted)
3️⃣ Cyclic References
Even circular references are handled correctly if they’re unreachable.
function createCycle() {
let a = {};
let b = {};
a.ref = b;
b.ref = a;
return;
}
createCycle(); // Both 'a' and 'b' become unreachable after function ends
Both objects will still be garbage collected because they are no longer reachable.
4️⃣ What You Can Do
You don’t control garbage collection directly, but you can:
- Avoid unnecessary global variables
- Nullify references when done (
obj = null) - Be cautious with event listeners and closures that may keep memory alive
💡 In Short:
JavaScript’s garbage collector automatically frees memory by removing unreachable objects using algorithms like mark-and-sweep, keeping your app memory-efficient without manual cleanup.