Skip to content

Memory Leak

Quick summary

Your program keeps allocating memory without releasing it — over time, memory usage grows until the program slows or crashes.

Why this happens

  • References to objects are kept in global variables or caches that never clear

  • Event listeners are added but never removed

  • Closures capture variables that prevent garbage collection

Minimal example

✗ Broken code
const cache = [];
function process(item) {
  cache.push(item); // Never cleared — grows forever!
  return item.value;
}
✓ Fixed code
const cache = new Map();
function process(item) {
  cache.set(item.id, item);
  if (cache.size > 1000) {
    // Clear old entries to bound memory
    const firstKey = cache.keys().next().value;
    cache.delete(firstKey);
  }
  return item.value;
}

The cache array grows without bound, leaking memory. Using a Map with a size limit and removing old entries bounds memory usage while still caching recent items.

How to diagnose

  • Monitor memory usage over time — does it keep growing?

  • Use browser DevTools memory profiler to find retained objects

  • Look for global variables, caches, or event listeners that accumulate

How to fix

  • Remove references to objects when they are no longer needed

  • Remove event listeners with removeEventListener when elements are destroyed

  • Use WeakMap/WeakSet for caches that allow garbage collection

How to prevent

  • Always clean up event listeners, timers, and subscriptions

  • Avoid global variables for storing data

  • Use weak references for caches

Related Resources

Related Glossary

Related Lessons

← Back to language