CodePark/ questions / Errors & memory
START PRACTICINGPRACTICE
Frontend question · JavaScript › Errors & memory

What causes memory leaks in JavaScript applications, and how do you find them?

A memory leak happens when something you no longer need is still reachable, so it cannot be freed. You find leaks by comparing heap snapshots in Chrome DevTools.

JavaScript uses garbage collection (GC). The engine frees an object when it can no longer be reached from roots, such as global variables and the active call stack.

Common causes:

  • event listeners added to window or long-lived elements and never removed
  • setInterval timers or subscriptions (WebSocket, observers, stores) that are never cleared, for example a React effect without a cleanup function
  • caches or maps that grow forever
  • detached DOM nodes: removed from the page but still referenced from JavaScript
  • closures that capture large objects and are kept alive by a listener
  • accidental global variables

Fixes:

  • Pair every subscription with a cleanup.
  • Use AbortController to remove listeners.
  • Put a limit on caches.
  • Use WeakMap for metadata about objects.

Finding leaks: take a heap snapshot in Chrome DevTools. Repeat an action, like opening and closing a modal. Take another snapshot and compare which objects are still kept. Allocation timelines also help.

  • Garbage collection (GC) frees objects that cannot be reached. A leak is an object that stays reachable by mistake.
  • Common causes are listeners never removed, and timers or subscriptions never cleared.
  • Other causes are caches with no limit, detached DOM nodes, captured closures and accidental globals.
  • Clean up in effects and on unmount. Use AbortController and WeakMap.
  • Find leaks with DevTools heap snapshots and allocation timelines.