JavaScript
/Advanced
Garbage Collection
Definition
Garbage Collection is a form of automatic memory management. The garbage collector attempts to reclaim memory which was allocated by the program, but is no longer referenced (used) by the application.
Explain Like I'm New
Imagine your computer's memory is a hotel. When variables are created, they check into rooms. When your code stops using those variables (like a function finishing), the 'Garbage Collector' (the hotel maid) sees that the room is empty and cleans it out so new guests can use it.
Real World Example
If you build an app that runs for days (like a dashboard), and you keep adding event listeners without removing them when components hide, those elements stay 'checked in' to the hotel. Eventually, the hotel gets full and the app crashes. This is called a Memory Leak.
Common Use Cases
- •Understanding memory leaks to prevent app crashes over time
- •Writing performant code for long-running Single Page Applications (SPAs)
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- Does JavaScript require manual memory allocation (like C or C++)?
- What is a Memory Leak?
intermediate
- What is the 'Mark-and-Sweep' algorithm?
- How do closures contribute to memory leaks?
advanced
- Name three common causes of memory leaks in JavaScript.
- How does the browser determine if an object is 'reachable'?
trick
- Can you force the JavaScript Garbage Collector to run manually?