JavaScript uses automatic garbage collection (GC) to manage memory — it allocates memory when objects are created and frees it when they’re no longer reachable.
However, memory leaks occur when references to unused objects are accidentally kept alive, preventing GC from reclaiming that memory.
🧩 1️⃣ How Garbage Collection Works
The JavaScript engine (like Chrome’s V8) uses the mark-and-sweep algorithm:
- Mark: It starts from the root objects (like the global scope) and marks everything reachable.
- Sweep: Anything unreachable is considered garbage and gets deleted.
So, if something is still referenced, it’s not collected — even if it’s no longer needed.
⚠️ 2️⃣ Common Causes of Memory Leaks
a) Global Variables
Variables accidentally declared without let, const, or var become global and stay in memory.
function badExample() {
leak = "I’m global now!";
}
✅ Fix: Always declare variables properly.
b) Forgotten Timers or Intervals
If you start a setInterval() or setTimeout() and never clear it, the callback and its references stay in memory.
setInterval(() => console.log("Still running..."), 1000);
✅ Fix:
const interval = setInterval(...);
clearInterval(interval);
c) Detached DOM Elements
If you remove an element from the DOM but still hold a reference in JavaScript, it can’t be garbage collected.
let button = document.getElementById("myBtn");
button.remove(); // removed from DOM
console.log(button); // still in memory!
✅ Fix: Set references to null after removal.
button = null;
d) Closures Holding References
Closures can “trap” variables in memory even after they’re no longer needed.
function createLeak() {
const bigData = new Array(1000000).fill("data");
return () => console.log(bigData.length);
}
const leaky = createLeak(); // bigData never gets garbage collected
✅ Fix: Nullify or avoid unnecessary captured variables.
e) Event Listeners
Unremoved event listeners keep references to DOM nodes.
const btn = document.getElementById("btn");
btn.addEventListener("click", () => console.log("Clicked"));
btn.remove(); // listener still active!
✅ Fix: Remove listeners before deleting elements.
btn.removeEventListener("click", handler);
🚀 3️⃣ How to Detect and Fix Memory Leaks
- Browser DevTools → Performance → Memory tab
- Use Heap Snapshots to detect objects that stay in memory.
- Tools: Chrome DevTools, Node.js
--inspectflag, memory profiling tools.
💡 In Short:
JavaScript automatically frees unused memory using garbage collection,
but memory leaks still happen when objects remain unintentionally referenced —
commonly through globals, timers, closures, or event listeners.
Always clean up references, timers, and listeners to prevent leaks.