Memory Leaks & Garbage CollectionAdvanced
1Question 1 of 1
javascriptHow does Garbage Collection work in V8 and what causes memory leaks in JavaScript?
Explanation & Concept
JavaScript engines like V8 use an automatic Garbage Collector (GC) based primarily on the **Mark-and-Sweep** algorithm: memory is reclaimed if an object is unreachable from any active root reference (global variables, call stack frames).
Common memory leaks occur when references are unintentionally retained: 1. Forgotten event listeners on removed DOM elements. 2. Uncleared `setInterval` or `setTimeout` timers. 3. Closures retaining large unneeded outer variables. 4. Detached DOM nodes referenced in JavaScript arrays.
Code Example
javascript
// Memory Leak Example: Forgotten timer retaining parent scope
function startMonitoring() {
const largeDataBuffer = new Array(1000000).fill("leak_data");
// LEAK: Timer runs forever in the background retaining largeDataBuffer
const timerId = setInterval(() => {
console.log("Checking status...");
}, 1000);
// FIX: Provide a clean-up method to cancel timer and allow GC
return () => clearInterval(timerId);
}
const stop = startMonitoring();
// Later when component unmounts:
stop(); // Timer cleared, largeDataBuffer can be garbage collected!How It Works & Key Takeaways
Always clear timers and remove event listeners when components unmount to allow the GC to collect captured references.
Mock Test · 1 Questions · Optional
Ready for Modules (ESM vs CommonJS)?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions