Memory, Cleanup and Garbage Collection

Updated · 13 min read
hardES2026javascriptmemorygarbage-collectionweakrefusing

JavaScript manages memory automatically: you create objects, and a garbage collector frees them when they are no longer needed. "No longer needed" has a precise meaning: an object is collected when it is no longer reachable from the program's roots. Memory problems in JavaScript are therefore almost always leaks: references you forgot about (an event listener, a timer, a cache, a closure) that keep objects reachable long after you stopped caring about them. This lesson explains reachability, the common leaks and how to find them, weak references, and the new using declarations for deterministic cleanup of resources like files and connections.

In One Minute

  • Objects stay in memory while they are reachable from roots (globals, the current call stack, active closures, registered listeners and timers).
  • Leaks are forgotten references: listeners never removed, intervals never cleared, ever-growing caches, closures capturing large data, detached DOM nodes.
  • WeakMap, WeakSet and WeakRef hold objects without keeping them alive.
  • FinalizationRegistry can run cleanup after an object is collected, but timing isn't guaranteed: never rely on it for correctness.
  • using and await using (stage 4, expected in ES2027, already in Node.js 26 and Chrome) dispose resources automatically at the end of a block.

Reachability

The garbage collector starts from roots and follows every reference; anything it can reach is kept, everything else is garbage:

Roots includeExample
Global variablesglobalThis.cache
Local variables and arguments of functions currently runningEverything on the call stack
Variables captured by closures that are themselves reachableA callback's remembered variables
Registered callbacksEvent listeners, pending timers, promise reactions waiting to run
The DOM tree (browsers)Elements in the document
reachability.js
let student = { name: "Navika", payments: new Array(100_000).fill(120) };
// The object is reachable through the variable `student`.
 
const report = { owner: student };
// Now it's reachable two ways.
 
student = null;
// Still reachable through report.owner: not collected.
 
report.owner = null;
// No more references: the object is garbage and will be collected eventually.

Collection happens when the engine decides, not when the last reference disappears, and you can't force it from normal code. Circular references aren't a problem: two objects that refer only to each other, but are unreachable from roots, are collected together (this is why modern collectors trace from roots instead of counting references).

Common Leaks

Event Listeners and Timers

A listener or timer keeps its callback alive, and the callback keeps everything it captures alive:

listener-leak.js
function openReport(panel, bigData) {
  // LEAK: the interval keeps running (and keeps bigData alive) after the panel closes.
  setInterval(() => updateTotals(panel, bigData), 1000);
 
  // LEAK: the window listener keeps bigData alive forever.
  window.addEventListener("resize", () => layout(panel, bigData));
}

The fix is to remove what you add, ideally all at once with an AbortController:

listener-fixed.js▶ Try it
function openReport(target, bigData) {
  const controller = new AbortController();
  const { signal } = controller;
 
  const timer = setInterval(() => target.dispatchEvent(new Event("tick")), 5);
  signal.addEventListener("abort", () => clearInterval(timer));
  target.addEventListener("tick", () => { bigData.ticks++; }, { signal });
 
  return () => controller.abort();
}
 
const target = new EventTarget();
const data = { ticks: 0 };
const close = openReport(target, data);
 
await new Promise((r) => setTimeout(r, 30));
close();
const ticksAtClose = data.ticks;
await new Promise((r) => setTimeout(r, 30));
console.log("ticked while open:", ticksAtClose > 0, "| stopped after close:", data.ticks === ticksAtClose);
Output
ticked while open: true | stopped after close: true

One abort() clears the interval and removes the listener, releasing every reference they held.

Unbounded Caches

A Map used as a cache keeps every key and value forever unless you remove them:

bounded-cache.js▶ Try it
class LruCache {
  #map = new Map();
  constructor(limit) { this.limit = limit; }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    this.#map.set(key, value);
    if (this.#map.size > this.limit) this.#map.delete(this.#map.keys().next().value);
  }
  get size() { return this.#map.size; }
}
 
const cache = new LruCache(3);
for (const id of [1, 2, 3, 4, 5]) cache.set(id, `report ${id}`);
cache.get(3);
cache.set(6, "report 6");
console.log(cache.size, cache.get(1), cache.get(3), cache.get(4));
Output
3 undefined report 3 undefined

This least recently used (LRU) cache keeps at most three entries, dropping the one used longest ago. (A Map remembers insertion order, so re-inserting on access moves a key to the end.) For caches keyed by objects, a WeakMap frees entries automatically when the object is gone.

Closures Capturing Too Much

A long-lived closure keeps alive whatever it references:

closure-capture.js
function makeSummary(allPayments) {          // allPayments: a huge array
  const count = allPayments.length;
  return () => `${count} payments`;          // captures only `count`: allPayments can be freed
}
 
function makeSummaryLeaky(allPayments) {
  return () => `${allPayments.length} payments`;   // keeps the whole array alive
}

Compute the small value you need first, and capture that.

Detached DOM Nodes

In browsers, an element removed from the page but still referenced by a variable, a Map or a listener stays in memory, along with its whole subtree. DevTools memory snapshots label these "Detached".

detached.js
const rowsById = new Map();
function addRow(id, el) { rowsById.set(id, el); table.append(el); }
function removeRow(id) {
  rowsById.get(id).remove();
  rowsById.delete(id);   // without this line, the removed row stays in memory
}
LeakFix
Listeners never removed{ signal } and controller.abort(), or removeEventListener
Intervals never clearedKeep the ID; clearInterval on cleanup
Growing caches and mapsSize limits (LRU), expiry, or WeakMap for object keys
Closures holding big dataCapture only what's needed
Detached DOM nodesDelete references when removing elements
Accidental globalsStrict mode and modules

Finding Leaks with DevTools

  1. Open DevTools, Memory panel, choose Heap snapshot, and take a snapshot.
  2. Perform the action you suspect leaks (open and close the report panel) several times.
  3. Take another snapshot and choose Comparison view: look for object counts that keep growing (Detached HTMLDivElement, your class names).
  4. Select an object and read its Retainers: the chain of references keeping it alive points straight at the leak.

The Performance panel with "Memory" checked shows heap size over time: a sawtooth pattern (rising, then dropping at each collection) is healthy; a staircase that never drops back suggests a leak. In Node.js, node --inspect gives the same tools, and process.memoryUsage() reports heap size.

Weak References

WeakMap and WeakSet

As the WeakMap lesson showed, they hold object keys weakly: an entry disappears when its key object becomes unreachable elsewhere. They're the right tool for metadata and caches attached to objects.

WeakRef

A WeakRef holds a weak reference to a single object. deref() returns the object if it's still alive, or undefined if it has been collected:

weakref.js▶ Try it
let report = { title: "Year-end report", rows: new Array(1000).fill(0) };
const ref = new WeakRef(report);
 
console.log(ref.deref()?.title);
report = null;
console.log(typeof ref.deref());
Output
Year-end report
object

Explanation: after report = null, the object is collectable, but collection hasn't happened yet (it usually won't happen within the same task), so deref() still returns it. Code using WeakRef must always handle both cases, because whether the object is still there depends on the garbage collector's timing.

FinalizationRegistry

A FinalizationRegistry lets you register a callback to run some time after an object has been collected, for example to release a related resource:

finalization.js
const registry = new FinalizationRegistry((label) => {
  console.log(`${label} was collected`);     // may run much later, or never
});
registry.register(bigObject, "report cache entry");

The specification makes no guarantee about when, or even whether, finalization callbacks run (a program may exit first). Use them only as a backstop for cleanup that also happens explicitly, never for program logic.

Deterministic Cleanup with using

Some objects hold resources that must be released promptly: file handles, database connections, locks, temporary directories. Garbage collection is too unpredictable for those. Explicit resource management adds using declarations: when the enclosing block ends, for any reason (normal exit, return, break or an exception), the resource's [Symbol.dispose]() method is called automatically:

using.js▶ Try it
class PaymentBatch {
  constructor(name) {
    this.name = name;
    console.log(`open ${name}`);
  }
  add(amount) { console.log(`  ${this.name}: add $${amount}`); }
  [Symbol.dispose]() {
    console.log(`close ${this.name}`);
  }
}
 
function processDay() {
  using morning = new PaymentBatch("morning");
  using evening = new PaymentBatch("evening");
  morning.add(120);
  evening.add(85);
  if (evening) throw new Error("card network down");
}
 
try {
  processDay();
} catch (err) {
  console.log("error:", err.message);
}
Output
open morning
open evening
  morning: add $120
  evening: add $85
close evening
close morning
error: card network down

Explanation: even though processDay threw, both batches were closed, in reverse order of creation (like nested try...finally blocks), before the error reached the caller. Without using, this needs a try...finally per resource.

await using does the same for resources with an asynchronous [Symbol.asyncDispose]() method, such as network connections; DisposableStack and AsyncDisposableStack collect several resources to dispose together:

await-using.js▶ Try it
class Connection {
  constructor(name) { this.name = name; }
  async query(sql) { return `${this.name} ran: ${sql}`; }
  async [Symbol.asyncDispose]() {
    await new Promise((r) => setTimeout(r, 5));
    console.log(`${this.name} disconnected`);
  }
}
 
async function loadTotals() {
  await using db = new Connection("payments-db");
  return await db.query("SELECT SUM(amount) FROM payments");
}
 
console.log(await loadTotals());
 
{
  using stack = new DisposableStack();
  stack.defer(() => console.log("temp file deleted"));
  stack.defer(() => console.log("lock released"));
  console.log("doing work with two resources");
}
Output
payments-db disconnected
payments-db ran: SELECT SUM(amount) FROM payments
doing work with two resources
lock released
temp file deleted

The connection was disconnected (asynchronously) before loadTotals returned its result. The stack ran its deferred callbacks in reverse order when the block ended.

In Practice

The Fee Tracker's report panel ties everything together: listeners and timers share one AbortController, an object-keyed cache uses a WeakMap, and a temporary export file is a disposable resource, so nothing outlives the panel:

panel.js▶ Try it
const summaryCache = new WeakMap();
function summaryOf(student) {
  if (!summaryCache.has(student)) summaryCache.set(student, `${student.name}: $${student.balance}`);
  return summaryCache.get(student);
}
 
class TempExport {
  constructor() { this.lines = []; console.log("temp export created"); }
  write(line) { this.lines.push(line); }
  [Symbol.dispose]() { console.log(`temp export removed (${this.lines.length} lines)`); }
}
 
function openPanel(events, students) {
  const controller = new AbortController();
  events.addEventListener("refresh", () => console.log(students.map(summaryOf).join(" | ")), { signal: controller.signal });
  return {
    exportCsv() {
      using file = new TempExport();
      for (const s of students) file.write(`${s.name},${s.balance}`);
      return file.lines.join("\n");
    },
    close: () => controller.abort(),
  };
}
 
const events = new EventTarget();
const panel = openPanel(events, [{ name: "Navika", balance: 120 }, { name: "Advitha", balance: 45 }]);
events.dispatchEvent(new Event("refresh"));
console.log(panel.exportCsv().split("\n").length, "rows exported");
panel.close();
events.dispatchEvent(new Event("refresh"));
console.log("no output after close");
Output
Navika: $120 | Advitha: $45
temp export created
temp export removed (2 lines)
2 rows exported
no output after close

Common Mistakes

Adding listeners or intervals without removing them. Pair every setup with a teardown; use AbortController.

Caches that only grow. Bound them, expire entries, or use WeakMap.

Relying on garbage collection timing. WeakRef.deref() may or may not return the object; finalizers may never run.

Manual try...finally for every resource. Where supported, using is shorter and can't forget a resource.

Under the Hood

V8 uses a generational garbage collector, named Orinoco. New objects are allocated in a small young generation, which is collected often and quickly by the Scavenger: it copies surviving objects elsewhere and discards the rest, so short-lived objects (most of them) cost almost nothing. Objects that survive two scavenges move to the old generation, collected less often by a mark-compact collector: it marks everything reachable from roots, sweeps the rest, and compacts memory to reduce fragmentation. To avoid long pauses, V8 does much of the marking incrementally and concurrently on background threads while your JavaScript runs, and runs the final steps when the page is idle. That's why WeakRef results don't change mid-task: the engine keeps any object you deref() alive until the end of the current task, so code can't observe collection happening in the middle of a function.

Interview Corner

How does garbage collection work in JavaScript?

Engines use tracing collectors: starting from roots (globals, the stack, closures, registered callbacks), they mark every reachable object and free the rest. Unreachable cycles are collected too. V8 is generational: frequent, cheap collections of new objects, and less frequent mark-compact collections of long-lived ones, done largely incrementally and concurrently.

What causes memory leaks in JavaScript?

Unintended references that keep objects reachable: event listeners and timers never removed, unbounded caches and maps, closures capturing large data, detached DOM nodes still referenced, and accidental globals. Fix by pairing setup with teardown (AbortController, clearInterval), bounding caches or using WeakMap, and dropping references.

What does using do?

A using declaration binds a disposable resource to a block; when the block exits by any path, the resource's [Symbol.dispose]() is called, in reverse order of declaration. await using awaits [Symbol.asyncDispose](). It replaces manual try...finally cleanup. It is stage 4, expected in ES2027, and shipping in Node.js 26 and Chrome.

Practice

Challenge: Write a Timer class whose constructor starts an interval and whose [Symbol.dispose]() clears it, then show with using that the interval stops when the block ends.

Show solution
timer-dispose.js▶ Try it
class Timer {
  ticks = 0;
  constructor(ms) { this.id = setInterval(() => this.ticks++, ms); }
  [Symbol.dispose]() { clearInterval(this.id); }
}
 
let timer;
{
  using t = new Timer(5);
  timer = t;
  await new Promise((r) => setTimeout(r, 30));
}
const afterBlock = timer.ticks;
await new Promise((r) => setTimeout(r, 30));
console.log("ticked:", afterBlock > 0, "| stopped:", timer.ticks === afterBlock);
Output
ticked: true | stopped: true

Quick check: Memory

3 questions
1When is an object eligible for garbage collection?
2Which is a common memory leak?
3What does a using declaration guarantee?

Key Takeaways

TaskTool
Remove many listeners{ signal } + controller.abort()
Stop a timerclearInterval(id)
Cache per objectWeakMap
Bounded cacheLRU with a Map and a size limit
Find a leakDevTools heap snapshots, Retainers
Release a resourceusing x = resource with [Symbol.dispose]()

Was this tutorial helpful?

Lesson 117 of 139