Where Do Variables Go?
In JavaScript, we don't need to manually allocate and free memory (like in C or C++). The engine does this for us using a Garbage Collector.
1. Core Principle: Reachability
The collector removes from memory anything that is no longer " reachable " . If an object cannot be referenced from the root (e.g., from a global variable), it is considered garbage.
2. Mark-and-Sweep Algorithm
- The collector takes the " roots " (global variables, current call stack).
- It marks them and all the objects they reference.
- It continues following references until it marks everything reachable.
- All unmarked objects are deleted.
3. Weak References (Briefly)
Sometimes we need to hold a reference to an object, but in a way that the collector can delete it if it's no longer needed anywhere else. Data structures like WeakMap exist for this (we will study them later).
The Garbage Collector runs automatically. You cannot predict the exact moment of cleanup or trigger it with a command in the browser. This is done for system stability.
Although " memory leaks " in JS happen less often than in older languages, they are possible — for example, if you forgot to remove an event listener or keep adding data to an array endlessly.