HardConcept

How do you find and fix memory leaks in JavaScript?

Technology:
JavaScript
Experience:
Senior

Quick answer

Take heap snapshots in Chrome DevTools before and after the suspect action, compare what grew, and fix the retaining reference, which is usually a forgotten listener, timer, global variable or unbounded cache.

Detailed explanation

JavaScript uses garbage collection based on reachability: an object is freed only when nothing reachable still references it. A leak is memory that your app no longer needs but something still references.

The usual causes are event listeners that are never removed, setInterval callbacks that are never cleared, detached DOM nodes held in a variable, accidental globals, closures that capture large objects, and caches or maps that only grow. In React, a missing cleanup function in useEffect is the most common source.

To diagnose, open the DevTools Memory tab, take a snapshot, repeat the action several times, take another and use the comparison view to see which object types keep growing. The retainers panel shows the chain of references keeping an object alive. Fixes are to remove listeners and timers in cleanup code, use WeakMap or WeakRef for caches keyed by objects, and put a size limit or eviction policy on caches.

Example

javascript
useEffect(() => {
  const onResize = () => setWidth(window.innerWidth);
  window.addEventListener("resize", onResize);
  const id = setInterval(refresh, 5000);

  return () => {                       // cleanup prevents the leak
    window.removeEventListener("resize", onResize);
    clearInterval(id);
  };
}, []);

Key points

  • Leak = unneeded but still reachable
  • Compare heap snapshots to see what keeps growing
  • Always pair listeners and timers with cleanup

Follow-up questions

  • What is the difference between WeakMap and Map?
  • How does mark-and-sweep garbage collection work?
  • HTMLMedium

    What is the difference between async and defer on script tags?

    Both download the script without blocking HTML parsing. defer waits until parsing finishes and runs scripts in document order; async runs a script as soon as it is downloaded, which can be before or after parsing and in any order.

    Mid-level · Senior · Browser & DOM
  • HTMLMedium

    How does the browser render a web page?

    The browser parses HTML into a DOM and CSS into a CSSOM, combines them into a render tree, computes layout (reflow), paints pixels and composites layers onto the screen.

    Mid-level · Senior · Browser & DOM
  • HTMLHard

    What are Core Web Vitals and how do you improve them?

    Core Web Vitals are Google’s field metrics for real-user experience: LCP (loading), INP (interactivity) and CLS (visual stability). They influence search ranking and are measured on real devices, not only Lighthouse.

    Senior · Performance
  • JavaScriptMedium

    What is event delegation in JavaScript?

    Event delegation means attaching one listener to a parent element and using event bubbling to handle events from its children, instead of adding a listener to each child.

    Junior · Mid-level · Browser & DOM
  • JavaScriptMedium

    What is the event loop in JavaScript and how does it work?

    The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.

    Mid-level · Senior · Asynchronous Programming