logo

Memory Leaks

Common causes of memory leaks in JS apps and detection/mitigation strategies.

Short explanation

Leaks occur when memory remains reachable due to lingering references (closures, globals, forgotten timers) and are harmful in long-running apps.

Real-world example

const cache = new Map();
function fetchAndCache(key) {
  if (!cache.has(key)) cache.set(key, fetchFromNetwork(key));
}
// If cache grows unbounded, memory usage rises

How JS handles it internally

The garbage collector can't reclaim memory that is still reachable. Profilers and heap snapshots help find retained objects and paths preventing GC.

FAQ

Q: How do I detect leaks?

A: Use browser devtools heap snapshots, track allocations over time, and look for unexpected retained objects and increasing memory graphs.