What Qualifies as a Memory Leak in JavaScript
You'll learn what actually constitutes a memory leak in a garbage-collected language like JavaScript.
The Paradox of GC Leaks
In a language with automatic garbage collection, you might think memory leaks are impossible—after all, the GC cleans up unreachable objects automatically. However, leaks happen when objects remain reachable (and thus uncollectable) even though your application no longer needs them.
The Key Distinction
A memory leak in JavaScript isn't about forgetting to "free" memory (that's the GC's job). It's about accidentally keeping references alive that prevent the garbage collector from doing its job.
Think of it like books in a library: the librarian (GC) can only discard books that have no checkout cards pointing to them. If you forget a checkout card in your pocket pointing to a book you'll never read again, that book stays on the shelf forever—not because the librarian is broken, but because they correctly see it as "still in use."
Common Leak Scenarios
Memory leaks occur when:
- Global variables accumulate data indefinitely
- Event listeners remain attached to removed DOM elements
- Closures capture and hold references to large objects unnecessarily
- Timers (
setInterval) keep running and holding references after they're no longer needed - Detached DOM trees are referenced in JavaScript but removed from the page
- Cache objects grow without bounds
The object is technically reachable (there's a reference chain from a root), so GC won't collect it—but your application logic has "forgotten" about it.
Key Takeaway: A JavaScript memory leak occurs when objects remain reachable through reference chains despite being logically unused by your application, preventing garbage collection from reclaiming that memory.