23. Memory Management
Memory Management
Low-level languages like C require you to manually allocate and free up RAM. JavaScript is a high-level language; it handles memory automatically using a process called Garbage Collection.
🗑️ Garbage Collection (Mark and Sweep)
JavaScript uses the "Mark-and-Sweep" algorithm. The engine periodically starts at the root (the Global Window object). It traces every single reference and "marks" objects that are still reachable. Any object in memory that cannot be reached is considered garbage, and the engine "sweeps" it away, freeing up RAM.
⚠️ Memory Leaks
A memory leak occurs when your app no longer needs an object, but a stray reference keeps it alive, preventing the Garbage Collector from sweeping it. If your app leaks memory, the browser will eventually crash.
Common Causes of Memory Leaks:
- Uncleared Intervals: Using
setIntervaland forgetting to callclearIntervalwhen the component is destroyed. - Ghost Event Listeners: Attaching event listeners to DOM elements but not removing them when the element is deleted.
- Accidental Global Variables: Forgetting to use
letorconst, polluting the global window object forever.
Knowledge Check
Ready to test your understanding of 23. Memory Management?