How does JavaScript garbage collection work?
JavaScript's garbage collection is an automatic process that manages memory by removing objects that are no longer reachable or needed in the application.
Key Concepts
1. Memory Allocation
When you create objects, variables, or functions, memory is allocated to store these values.
let obj = { key: 'value' }; // Memory is allocated for 'obj'
2. Reachability
An object is considered "reachable" if it is:
- Referenced by a root (e.g.,
window
,global
). - Accessible via references from other reachable objects.
3. Garbage Collection Process
The garbage collector identifies and removes objects that are no longer reachable. The primary algorithm used is:
Mark-and-Sweep Algorithm
- Start with root objects (e.g., global variables, the call stack).
- Mark all reachable objects.
- Sweep and reclaim memory for unmarked (unreachable) objects.
let obj = { key: 'value' };
obj = null; // The object is now unreachable and will be collected.
Common Triggers for Garbage Collection
- Setting Variables to
null
orundefined
: Explicitly removing references.let data = { key: 'value' }; data = null; // Helps garbage collector reclaim memory.
- Out-of-Scope Variables: Variables in local functions are collected when the function exits.
function example() { let temp = 'data'; } // 'temp' is no longer reachable after the function ends.
Best Practices to Help Garbage Collection
-
Avoid Memory Leaks:
- Unintended references can prevent garbage collection.
- Example: Adding listeners without removing them.
let element = document.getElementById('button'); element.addEventListener('click', () => { console.log('Clicked!'); }); // If 'element' is not set to null, it may stay in memory. element = null; // Explicitly remove reference.
-
Use WeakMaps and WeakSets: These structures allow objects to be garbage-collected if no other references exist.
let weakMap = new WeakMap(); let obj = {}; weakMap.set(obj, 'value'); obj = null; // Object can be garbage-collected.
Conclusion
JavaScript's garbage collection ensures efficient memory management by reclaiming unused objects. While it works automatically, following best practices like managing references and avoiding memory leaks can improve performance and reliability.