JavaScript Memory Management
A dashboard works fine in testing. Then someone leaves it open in a tab all day, and by the afternoon scrolling stutters, the fan is spinning, and Chrome eventually shows the "Aw, Snap! Out of memory" page. Nothing threw an error. Nobody wrote malloc. The garbage collector was running the whole time, it just wasn't allowed to free anything.
That's the usual way memory problems show up in JavaScript. This post covers how the stack and heap work, how V8's garbage collector decides what to free, the five leak patterns I run into most, and how to track one down with Chrome DevTools.
Server-rendered pages reload on every navigation, so whatever leaked gets thrown away. A single-page app keeps the same JavaScript runtime for the whole session. If each route change leaks even a little, it adds up over a long session until GC pauses get noticeable and the tab eventually runs out of memory.
The JavaScript Memory Model
Whatever engine runs your code (V8 in Chrome and Node.js, SpiderMonkey in Firefox), you can think of memory as two areas: the call stack and the heap. Engines are free to optimize around this, but the mental model holds up well for debugging.
The Call Stack
The stack is a LIFO (last-in, first-out) structure for static data, meaning things whose size is known ahead of time:
- Primitive values:
number,boolean,string,null,undefined,symbol,bigint - References (pointers) to objects on the heap
- Function call frames (return addresses, local variables)
Stack access is fast because the memory is contiguous. When a function returns, its frame is popped and that space is reused right away. No garbage collector involved.
The Heap
Objects, arrays, closures and functions go on the heap, since their size isn't known until runtime and can grow. Allocating there is slower, and heap memory isn't freed just because a variable goes out of scope. Freeing it is the garbage collector's job.
JavaScript Memory Layout: Stack holds primitives and references; Heap holds objects and closures
// Primitives: stored on the STACK
let count = 42; // number on stack
let name = "Alice"; // string value on stack (in V8, short strings are interned)
let flag = true; // boolean on stack
// Objects: reference on stack, data on HEAP
let user = { name: "Alice", age: 30 }; // user variable (reference) lives on stack
// { name, age } object lives on heap
// Copying primitives creates independent values
let a = 10;
let b = a; // b is a new copy; changing a won't affect b
// Copying objects copies the REFERENCE, not the data
let obj1 = { x: 1 };
let obj2 = obj1; // both variables point to the SAME heap object
obj2.x = 99;
console.log(obj1.x); // 99, same object!
Garbage Collection: How V8 Frees Memory
The garbage collector (GC) reclaims heap memory your program can no longer reach. The important word is "reach". The GC doesn't know whether you still need an object, only whether something still points to it.
Reference Counting (Legacy, Don't Rely On It)
Older engines kept a reference count per object and freed it when the count hit zero. That breaks on circular references: if A points to B and B points to A, neither count ever reaches zero, even when nothing else can reach them. Old Internet Explorer versions leaked this way when JS objects and DOM nodes referenced each other.
Mark-and-Sweep (Modern Standard)
All modern JavaScript engines use mark-and-sweep (or variants of it). The algorithm has two phases:
- Mark phase: Starting from "roots" (global object, local variables in active stack frames), the GC traverses every reachable object and marks it as alive.
- Sweep phase: Any object that was not marked is considered unreachable and its memory is reclaimed.
This handles circular references fine. If two objects point at each other but nothing reachable points at them, neither gets marked, and both are collected.
V8's Generational Garbage Collector
V8 (Node.js, Chrome) uses a generational GC built on the observation that most objects die young. The heap is split into:
- Young generation (new space): Small (roughly 1 to 8 MB per semi-space, depending on version and settings). New objects are allocated here. Collected frequently and quickly by the Scavenger (minor GC). Objects that survive two collections are promoted to old space.
- Old generation (old space): Larger (~hundreds of MB). Contains long-lived objects. Collected less frequently by the Major GC (mark-sweep-compact). This is where GC pauses hurt most.
A major GC can pause JavaScript execution (a "stop-the-world" pause). V8 shortens these with incremental marking and concurrent sweeping, but lots of long-lived objects still means more frequent and longer pauses. Keep the old generation lean.
On the server, a leak ends with the process dying with FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory. Raising --max-old-space-size buys time, but if memory keeps climbing between requests, you only crash later. Also, in a container, if the memory limit is lower than the heap size Node is allowed to grow to, the kernel's OOM killer gets there first. Then you won't see that message at all, just a container that exited with code 137.
Common Memory Leaks and How to Fix Them
Almost every JavaScript leak is the same bug in different clothes: an object stays reachable because some reference that should have been dropped wasn't.
1. Accidental Global Variables
Assign to an undeclared variable in sloppy mode and you've created a property on the global object, which lives as long as the page does. ES modules and classes are strict by default, so this mostly bites in older scripts.
// LEAK: 'data' becomes window.data and is never collected
function processData() {
data = fetchLargeDataset(); // forgot 'let' or 'const'
}
// FIX: always declare variables
function processData() {
const data = fetchLargeDataset(); // local, freed when function returns
}
// Also add 'use strict' at the top of your scripts:
// it turns accidental globals into ReferenceError at runtime
'use strict';
2. Forgotten Timers and Intervals
A setInterval callback holds a reference to everything in its closure. If you never call clearInterval, the closure lives forever, and so does everything it references.
// LEAK: heavyData is captured by the interval closure and never freed
function startMonitor() {
const heavyData = loadLargeConfig(); // 50 MB object
setInterval(() => {
updateDashboard(heavyData);
}, 1000);
// interval runs forever; heavyData can never be GC'd
}
// FIX: store the ID and clear when no longer needed
function startMonitor() {
const heavyData = loadLargeConfig();
const intervalId = setInterval(() => {
updateDashboard(heavyData);
}, 1000);
// Return a cleanup function (common in React useEffect, for example)
return () => clearInterval(intervalId);
}
// In a React component:
useEffect(() => {
const cleanup = startMonitor();
return cleanup; // called when component unmounts
}, []);
3. Closures Holding Stale References
A closure keeps its outer variables alive for as long as the closure itself is reachable. That's the point of closures, and it's also how a tiny function ends up pinning a huge array in memory.
// LEAK: the returned closure keeps 'hugeArray' alive
function createProcessor() {
const hugeArray = new Array(1_000_000).fill('data');
// Only 'hugeArray.length' is needed, but the entire array
// stays in memory because the closure captures the outer scope
return function process() {
return hugeArray.length;
};
}
// FIX: extract only the data you need
function createProcessor() {
const hugeArray = new Array(1_000_000).fill('data');
const length = hugeArray.length; // capture the primitive
// hugeArray can now be GC'd once createProcessor() returns
return function process() {
return length;
};
}
4. Detached DOM Nodes
When you remove a DOM element but still hold a JavaScript reference to it, the element and its entire subtree remain in memory even though it's no longer in the document.
// LEAK: 'cachedList' keeps the detached subtree alive
let cachedList;
function buildList(items) {
cachedList = document.getElementById('list'); // save reference
cachedList.innerHTML = items.map(i => `${i} `).join('');
}
function replaceList(newItems) {
const container = document.getElementById('container');
container.removeChild(cachedList); // removed from DOM...
// but cachedList still holds a reference, so the subtree can't be GC'd!
buildList(newItems);
}
// FIX: null out the reference once the element is removed
function replaceList(newItems) {
const container = document.getElementById('container');
container.removeChild(cachedList);
cachedList = null; // allow GC to collect the old subtree
buildList(newItems);
}
5. Event Listeners Not Removed
An element holds a strong reference to each listener attached to it, and the listener holds everything in its closure. The worst case is a listener on a long-lived target like window or document whose handler references a component that's already been torn down. The component can't be collected until you remove the listener.
One gotcha: calling addEventListener twice with the same function reference is a no-op the second time. Inline arrow functions are new functions on every call, so they stack up, and you can't remove them later because you no longer have the reference.
// LEAK: the listener is never removed, so handleClick stays attached for the element's lifetime
function init(element) {
element.addEventListener('click', handleClick);
}
// FIX 1: remove listener explicitly when done
function init(element) {
element.addEventListener('click', handleClick);
return () => element.removeEventListener('click', handleClick);
}
// FIX 2: use { once: true } for one-shot handlers
element.addEventListener('click', handleClick, { once: true });
// automatically removed after first invocation
// FIX 3: use AbortController for bulk cleanup (great for SPAs)
const controller = new AbortController();
element.addEventListener('click', handleClick, { signal: controller.signal });
window.addEventListener('resize', handleResize, { signal: controller.signal });
// Removes ALL listeners registered with this controller at once
controller.abort();
Detecting Memory Leaks with Chrome DevTools
Recognizing the patterns helps, but you still need to prove there's a leak and find what's holding on. Heap snapshot comparison in Chrome DevTools is the approach I'd start with.
Open DevTools Memory Panel
Press F12, go to the Memory tab. Select "Heap snapshot" for a point-in-time analysis, or "Allocation instrumentation on timeline" to track allocations over time.
Take a Baseline Snapshot
Click Take snapshot before performing the action you suspect leaks (e.g., navigating to a page and back). This is your baseline (Snapshot 1).
Reproduce the Suspected Leak
Perform the action several times (navigate away and back, open and close a modal, etc.). Then take another snapshot (Snapshot 2). Repeat once more (Snapshot 3).
Compare Snapshots
Select Snapshot 3 and change the view to "Comparison". Objects with a high Delta that didn't exist in Snapshot 1 are the main suspects. Type Detached into the class filter to list DOM nodes that are out of the document but still retained, and sort by Retained Size.
Trace to Source
Click a suspicious object and look at its Retainers panel: the chain of references keeping it alive. Follow it up until you hit something you recognize (a module-level array, a listener, a closure variable). That's usually your bug. Close the console first, or clear it: anything you console.logged stays retained by DevTools and shows up as a false positive.
Open the Performance Monitor (DevTools → More tools → Performance monitor) and watch the JS heap size graph while using your app. A healthy app shows a sawtooth: allocations climb, then GC brings it back down. A leak looks like a ratchet, where the low point after each GC creeps higher with every action and never comes back.
WeakMap and WeakSet: Built for Memory Safety
A regular Map keyed by objects is a common way to leak: the map keeps every key alive. WeakMap and WeakSet (ES6) hold their keys weakly, so they don't stop the GC from collecting them. Once nothing else references a key, its entry goes away along with it.
| Feature | Map | WeakMap |
|---|---|---|
| Key types | Any value (string, number, object, ...) | Objects only |
| Prevents GC of keys? | Yes (strong reference) | No (weak reference) |
| Iterable / enumerable | Yes: for...of, .size |
No, not iterable |
| Best use case | General key→value caching | Per-object metadata, caches keyed by DOM nodes |
| Memory leak risk | High if keys are objects that get removed | Low: entries are dropped once their keys are collected |
// PROBLEM with Map: DOM nodes used as keys are never GC'd
const cache = new Map();
function processElement(el) {
cache.set(el, computeExpensiveData(el));
// even after el is removed from the DOM, cache keeps it alive
}
// SOLUTION with WeakMap: when el is GC'd, the entry disappears too
const cache = new WeakMap();
function processElement(el) {
if (!cache.has(el)) {
cache.set(el, computeExpensiveData(el));
}
return cache.get(el);
}
// Real-world use: memoizing computed styles per DOM node
const computedStyles = new WeakMap();
function getStyles(element) {
if (!computedStyles.has(element)) {
computedStyles.set(element, getComputedStyle(element));
}
return computedStyles.get(element);
}
// When the element is removed, computedStyles automatically cleans up
Memory Optimization Best Practices
Finding a leak in a heap snapshot takes far longer than not writing it. A few habits that help, roughly in order of how often I'd reach for them:
Keep variables in the smallest scope that works. const and let are block-scoped, so the reference is gone when the block exits. A var sticks around until the function returns. Modern engines are often smart about this anyway, but block scope makes lifetimes obvious to the next reader too.
// var leaks to function scope: data lives until fetchAll() returns
function fetchAll(ids) {
for (var i = 0; i < ids.length; i++) {
var result = fetchOne(ids[i]); // result not freed until end of fetchAll
process(result);
}
}
// const/let scoped to the block: result can be freed each iteration
function fetchAll(ids) {
for (let i = 0; i < ids.length; i++) {
const result = fetchOne(ids[i]); // freed at end of iteration
process(result);
}
}
If you create and throw away huge numbers of short-lived objects every frame (particles, game entities), an object pool reuses them and cuts GC pressure. I wouldn't do this in normal app code: V8's young-generation GC is very good at short-lived objects, and pooled objects end up in old space, where forgetting to release one is a leak of its own.
class ObjectPool {
constructor(factory, reset, initialSize = 10) {
this.factory = factory;
this.reset = reset;
this.pool = Array.from({ length: initialSize }, factory);
}
acquire() {
return this.pool.pop() ?? this.factory();
}
release(obj) {
this.reset(obj);
this.pool.push(obj);
}
}
// Example: particle system
const particlePool = new ObjectPool(
() => ({ x: 0, y: 0, vx: 0, vy: 0, life: 1 }),
p => { p.x = p.y = p.vx = p.vy = 0; p.life = 1; }
);
function spawnParticle(x, y) {
const p = particlePool.acquire();
p.x = x; p.y = y; p.vx = Math.random() - 0.5; p.vy = -Math.random();
return p;
}
function killParticle(p) {
particlePool.release(p); // return to pool instead of letting GC handle it
}
For large numeric datasets (image processing, audio, WebGL, simulations), use TypedArrays (Float32Array, Int32Array, etc.). They allocate one fixed-size contiguous block and skip the per-element overhead of regular arrays, which matters most when the values are floats (V8 would otherwise box them or store 8-byte doubles).
// Regular Array: each element is a tagged value (8 bytes on 64-bit V8, more if boxed)
const regular = new Array(1_000_000).fill(0); // ~8 MB or more in V8
// Float32Array: 4 bytes per element, no boxing overhead
const typed = new Float32Array(1_000_000); // ~4 MB
// Iteration is fast too: the JIT knows every element's type up front
function sumTyped(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) total += arr[i];
return total;
}
// SharedArrayBuffer for zero-copy sharing between workers
const sharedBuffer = new SharedArrayBuffer(4 * 1024 * 1024); // 4 MB
const workerView = new Float32Array(sharedBuffer);
// Pass sharedBuffer to a Worker, no copy needed (requires cross-origin isolation in browsers)
WeakRef (ES2021) holds a reference that doesn't prevent collection, and FinalizationRegistry lets you run a callback after an object is collected. Treat both as a last resort. The spec gives no guarantee about when, or even whether, the callback runs, so never use it to close sockets or files you actually need closed. Call an explicit close() for that.
// WeakRef: a reference that doesn't prevent GC
let obj = { data: 'important' };
const weakRef = new WeakRef(obj);
// Later...
obj = null; // obj can now be GC'd
const deref = weakRef.deref();
if (deref) {
console.log(deref.data); // still alive
} else {
console.log('object was collected');
}
// FinalizationRegistry: callback when object is collected
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Cleanup for: ${heldValue}`);
releaseExternalResource(heldValue);
});
let socket = openWebSocket('wss://example.com');
registry.register(socket, 'ws-connection-1');
// When socket is GC'd, releaseExternalResource('ws-connection-1') runs
When to Worry About Memory (and When Not To)
Most code doesn't need any of this. A marketing page, a form, a short-lived CLI script: the page reloads or the process exits, and whatever leaked is gone. I wouldn't add object pools or WeakRef tricks there. They make code harder to read and the GC already does a good job with short-lived objects.
It's worth caring when something lives for a long time: SPAs people keep open all day, dashboards on a wall screen, Electron apps, and long-running Node servers. For those, here's what I'd check before shipping:
Pre-Production Memory Checks
- Every subscribe has an unsubscribe. Intervals,
window/documentlisteners, WebSocket handlers and store subscriptions should be torn down in the component's cleanup. AnAbortControllerper component makes this one line. - Module-level caches have a limit. A
Mapat the top of a Node module that you only ever add to is a leak, just a slow one. Cap it (LRU) or switch to aWeakMapif keys are objects. - Mount and unmount a few times. Navigate to a heavy route and back five times, force a GC (the trash can icon in the Memory panel), and compare snapshots. If heap size keeps climbing, something's retained.
- Watch memory over time in production. For Node, graph
process.memoryUsage().heapUsed. A slow upward trend over days usually shows up long before the OOM crash does.
And don't use WeakMap as a general-purpose cache. You can't iterate it, check its size, or rely on when entries disappear. It's for attaching data to objects you don't own, not for deciding how much to keep in memory.