# Memory Leaks in JavaScript

> What causes memory leaks in JavaScript applications, and how do you detect and fix them in the browser and in Node.js?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What causes memory leaks in JavaScript applications, and how do you detect and fix them in the browser and in Node.js?

## Answer

A memory leak in JavaScript is memory that your program no longer needs but that the garbage collector cannot free because something still references it. JavaScript engines use reachability-based (mark-and-sweep) garbage collection, so a leak is almost always an unintended reference from a live root, such as a global variable, an active timer, an event listener, a closure or a long-lived cache. You find leaks with heap snapshots and allocation timelines in Chrome DevTools or the Node.js inspector, and fix them by removing the reference at the right lifecycle moment.

### How garbage collection decides what to keep

V8 starts from roots (the global object, the current call stack, active handles like timers and sockets) and marks everything reachable from them. Anything unmarked is swept. Circular references alone do not leak: two objects pointing at each other but unreachable from a root are collected. So the question is always "which root is still holding this?"

### The usual suspects

1. **Forgotten event listeners**: a component adds `window.addEventListener('resize', handler)` and never removes it. The handler's closure keeps the component's data alive after it unmounts.
2. **Timers and intervals**: `setInterval` callbacks run forever unless cleared, along with everything they close over.
3. **Detached DOM nodes**: an element removed from the page but still referenced by a JS variable, array or cache. The entire subtree stays in memory.
4. **Accidental globals**: assigning to an undeclared variable in sloppy mode creates a property on `window`. ES modules and strict mode turn this into a `ReferenceError`.
5. **Unbounded caches and maps**: a `Map` of session data or memoized results that only grows. Common in Node.js servers that run for weeks.
6. **Closures holding large data**: a small callback that captures a big array or response object it does not actually need.
7. **Subscriptions**: WebSocket, RxJS, Firebase or store subscriptions not unsubscribed on unmount.

### Detecting a leak

- **Symptom**: memory grows steadily across repeated actions (open and close a modal 20 times) and never drops after a forced GC.
- **Chrome DevTools Memory panel**: take a heap snapshot, repeat the action, take another, and use the Comparison view. Filter by "Detached" to find detached DOM trees. The Retainers pane shows the chain of references keeping an object alive.
- **Allocation instrumentation on timeline**: shows allocations that survive over time (blue bars that stay).
- **Performance monitor**: watch JS heap size and DOM node count live.
- **Node.js**: run with `--inspect` and use Chrome DevTools, log `process.memoryUsage().heapUsed`, write snapshots with `v8.writeHeapSnapshot()`, or use `--heapsnapshot-near-heap-limit`. A process that grows until "JavaScript heap out of memory" is the classic sign.

### Prevention patterns

| Leak source | Fix |
| --- | --- |
| Event listeners | `removeEventListener` in cleanup, or pass `{ signal }` from an `AbortController` and call `abort()` |
| Timers | `clearInterval` / `clearTimeout` in cleanup (React `useEffect` return) |
| Detached DOM | Null out references, or store element metadata in a `WeakMap` |
| Caches | LRU with a max size, TTLs, or `WeakMap` keyed by objects |
| Subscriptions | Always keep and call the unsubscribe function |

In React, the `useEffect` cleanup function is where nearly all of these fixes go.

**Mark-and-sweep, and what defeats it. Try the Map, setInterval and accidental-global leaks under Tweak.**

1. **Mark**: Everything reachable from the roots is marked.
2. **Sweep**: Unmarked objects are freed.
3. **Timer leak**: An un-cleared setInterval keeps its closure and captured data alive.
4. **Map and global leaks**: Strong Map keys and accidental globals stay reachable forever.

## Code examples

### Listener and timer leak fixed with AbortController and cleanup

```
// Leaky: listener and interval outlive the widget
function mountPriceTickerLeaky(el) {
  const history = new Array(100_000).fill(0); // big closure data
  window.addEventListener('resize', () => el.style.width = `${history.length}px`);
  setInterval(() => { el.textContent = `Rs ${Math.random().toFixed(2)}`; }, 1000);
}

// Fixed: one AbortController removes every listener; return a cleanup
function mountPriceTicker(el) {
  const controller = new AbortController();
  const { signal } = controller;

  window.addEventListener('resize', () => { /* resize logic */ }, { signal });
  el.addEventListener('click', () => { /* open details */ }, { signal });
  const timer = setInterval(() => { el.textContent = 'tick'; }, 1000);

  return function unmount() {
    controller.abort();     // removes both listeners
    clearInterval(timer);   // stops the timer and frees its closure
  };
}

// React equivalent
// useEffect(() => mountPriceTicker(ref.current), []);
```

Passing an AbortSignal to addEventListener lets you remove many listeners with one abort() call. Returning a cleanup function matches how React's useEffect expects teardown to work.

### Detached DOM and unbounded cache in Node.js

```
// Detached DOM: removed from the page but still referenced
const removedRows = [];
function deleteRow(row) {
  row.remove();
  removedRows.push(row); // leak: whole subtree stays in memory
}
// Fix: do not keep the node, or store metadata in a WeakMap keyed by it
const rowMeta = new WeakMap();

// Node.js: a per-request cache that only grows
const sessions = new Map();
function onRequest(req) {
  sessions.set(req.id, { body: req.body, at: Date.now() }); // never deleted
}

// Fix: evict on a schedule (or use an LRU / Redis with TTL)
const TTL_MS = 15 * 60 * 1000;
setInterval(() => {
  const now = Date.now();
  for (const [id, s] of sessions) if (now - s.at > TTL_MS) sessions.delete(id);
}, 60_000).unref(); // unref so the timer does not keep the process alive

setInterval(() => {
  const { heapUsed } = process.memoryUsage();
  console.log('heapUsed MB', (heapUsed / 1024 / 1024).toFixed(1));
}, 30_000).unref();
```

Arrays and Maps that hold DOM nodes or request data are the most common real leaks. Bounded eviction and logging heapUsed over time make growth visible before the process crashes.

## Key points

- A leak is unneeded memory that is still reachable from a GC root; circular references alone do not leak.
- Top causes: listeners, timers, detached DOM nodes, accidental globals, unbounded caches and closures holding large data.
- Detect with heap snapshot comparison, the Detached filter and the Retainers pane in Chrome DevTools.
- In Node.js use --inspect, process.memoryUsage() and v8.writeHeapSnapshot().
- AbortController signals and useEffect cleanup functions are the modern fixes for listener leaks.

## Common follow-up questions

- How does mark-and-sweep garbage collection work, and what is a generational GC?
- How would you find which object is retaining a detached DOM node?
- Why do circular references not cause leaks in modern engines?
- How can closures cause memory leaks?
- How would you debug a Node.js service whose memory grows until it crashes?

## Interview tips

- Describe a concrete debugging workflow (snapshot, repeat, compare, retainers) rather than just listing causes.
- Explain leaks in terms of reachability from roots; it shows you understand the GC model.
- If you have fixed a real leak, such as a listener not removed on unmount, mention it briefly.

## Concepts covered

Memory Leak, Garbage Collection, Mark-and-Sweep, Detached DOM, Event Listeners, Heap Snapshot

Previous: [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns) · Next: [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [WebSockets and Real-time Communication](https://www.internhack.in/learn/interview/javascript-interview/js-websockets)
- [Advanced Regular Expressions](https://www.internhack.in/learn/interview/javascript-interview/js-regex-advanced)
- [JavaScript Performance Optimization](https://www.internhack.in/learn/interview/javascript-interview/js-performance-optimization)
- [Tagged Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-tagged-templates)
- [Intersection Observer and Mutation Observer](https://www.internhack.in/learn/interview/javascript-interview/js-intersection-observer)
- [Async Iterators and for await...of](https://www.internhack.in/learn/interview/javascript-interview/js-async-iterators)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
