What is Garbage Collection?
You'll learn what garbage collection is and why JavaScript automates memory cleanup for you.
The Core Concept
When you create objects, arrays, functions, or any data in JavaScript, they occupy memory in your computer. Once you're done using that data — when no part of your program can access it anymore — that memory should be freed up for reuse. Otherwise, your application would gradually consume more and more memory until it crashes.
Garbage collection is the automatic process by which JavaScript identifies and reclaims memory that's no longer needed. You don't have to manually free memory like in languages such as C or C++. JavaScript's engine handles this cleanup for you behind the scenes.
Why We Need It
Imagine your program's memory as a warehouse. Every time you create an object, you're placing a box in that warehouse. If you never remove old boxes (objects you're done using), the warehouse fills up. JavaScript's garbage collector acts like an automated cleanup crew that periodically sweeps through, identifies boxes (objects) that nobody is using anymore, and removes them.
How It Knows What to Clean
The garbage collector tracks reachability: if there's no way to access a piece of data from your currently running code — no variable references it, no object property points to it — then it's considered "unreachable" and eligible for garbage collection.
You've already worked with references in closures, object properties, and scope chains. The GC follows those same connections to determine what's still "alive."
Key Takeaway:
Garbage collection is JavaScript's automatic memory management system that frees up memory occupied by unreachable data, preventing memory leaks without manual intervention.