Memory & Garbage Collection
Understand how JavaScript automatically manages memory, references, and the Mark-and-Sweep garbage collection algorithm.
Automatic Memory Management
Low-level languages like C require you to manually allocate and free memory in RAM. If you forget to free it, your app leaks memory and eventually crashes.
JavaScript handles this automatically using a **Garbage Collector (GC)**. When you create an object, JS allocates memory for it. When the object is no longer needed, the GC automatically detects it and frees the memory.
The Concept of Reachability
How does the GC know when an object is 'no longer needed'?
It uses the concept of **Reachability**. An object is reachable if you can trace a path to it starting from the 'roots' (like the global window object, or variables currently in scope).
If an object has zero references pointing to it from a root, it is unreachable. The GC considers it garbage.
The Mark-and-Sweep Algorithm
Modern JavaScript engines use a 'Mark-and-Sweep' algorithm.
1. **Mark**: The GC starts at the roots and traverses every single reference, 'marking' every object it finds as reachable.
2. **Sweep**: It then scans the entire memory heap. Any object that is *not* marked is immediately deleted, freeing up RAM.
javascript
let user = { name: 'Alex' };
// The object is reachable via the 'user' variable.
user = null;
// The reference is severed. The object is now unreachable and will be swept.
The Mark and Sweep
Study the architecture diagram below. It contrasts a healthy, reachable object graph with one that has had a reference severed, leaving a detached object stranded and targeted for deletion.
The Mark-and-Sweep Process
name: 'Alex',
profile: { avatar: 'pic.png' }
};
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- JavaScript automatically handles memory allocation and freeing via a Garbage Collector.
- The primary metric for memory retention is **Reachability**.
- If an object cannot be reached by following references from a root, it is garbage collected.
- Modern engines use the **Mark-and-Sweep** algorithm to find and delete unreachable objects.
- Memory leaks happen when you unintentionally maintain a reference to an object you no longer need (e.g., uncleared intervals or event listeners).
Done with this concept?
Mark it complete to track your progress. No login needed.