Topic 34 of 37
Garbage Collection & Memory Leaks
Overview
JavaScript has automatic Garbage Collection (using a Mark-and-Sweep algorithm). It cleans up objects that are no longer 'reachable' from the root. A memory leak occurs when you accidentally keep references to objects you no longer need, preventing the GC from freeing the memory.
Syntax
To fix these, always use clearInterval() and removeEventListener() during component teardown.
Common Memory Leak Causes
javascript
// 1. Uncleared Intervals
setInterval(() => {
// If the component using this is destroyed, this keeps running!
console.log("Leaking...");
}, 1000);
// 2. Lingering DOM Event Listeners
const btn = document.getElementById('btn');
btn.addEventListener('click', doSomethingHeavy);
// If 'btn' is removed from DOM but listener isn't explicitly removed, memory leaks.Common Pitfalls
- Using closures to store large datasets permanently in the global scope.
Interview Tips
- Explain the 'Mark-and-Sweep' algorithm: The GC starts at the root (window object) and marks everything it can reach. Everything unmarked is swept away.
Real-World Example
Using React's useEffect cleanup function to prevent leaks.
example
javascript
useEffect(() => {
const timer = setInterval(() => setTick(t => t+1), 1000);
// Cleanup function runs when component unmounts
return () => clearInterval(timer);
}, []);