Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 156 ยท Under the Hood

Memory Management and Garbage Collection

Learn how JavaScript stores values, how the call stack and garbage collector work, and how to find and fix memory leaks from listeners, timers and closures.

In languages like C you ask for memory and must give it back yourself. Forget, and the program leaks; give it back twice, and it crashes. JavaScript takes that job away from you: memory is reserved when you create values and freed automatically by a garbage collector when nothing can use them anymore.

"Automatic" doesn't mean "impossible to get wrong", though. A page that stays open for hours โ€” a dashboard, an email client, a single-page app โ€” can slowly fill up with objects that are no longer needed but are still reachable. In this lesson you'll look under the hood: the call stack and execution contexts, the stack and the heap, how the garbage collector decides what to free, and the handful of patterns that cause almost every real-world leak.

The call stack and execution contexts

Before memory, let's look at how code runs. Every time JavaScript runs a function, it creates an execution context: a record of that call's local variables, its this value, its arguments and where to return when it's done. These contexts are kept on the call stack, a last-in, first-out pile:

  1. When your script starts, the global context goes on the stack.
  2. Calling a function pushes a new context on top.
  3. When the function returns, its context is popped off, and execution continues in the one below.

JavaScript has only one call stack per thread, which is why it runs one thing at a time. It's also why an infinite recursion fails: each call pushes another context until the engine runs out of room and throws a RangeError: Maximum call stack size exceeded.

JS Watching the call stack

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The exact depth depends on the browser and on how much each call stores, which is why you should never rely on it. When the depth of your data is unknown, prefer loops over deep recursion.

What an execution context sets up

When a context is created, the engine first scans the function body and registers its declarations, and only then runs the code line by line. That two-step process explains hoisting: function declarations are ready before the first line runs, var variables exist early with the value undefined, and let/const variables exist but can't be touched until their line runs (the "temporal dead zone").

A context also remembers its outer environment: the scope where the function was defined. That link is what makes closures work โ€” and, as you'll see, it's also how closures can keep memory alive.

The stack and the heap

You'll often hear that JavaScript stores values in two places:

  • The stack holds each execution context's small, fixed-size data: local variable slots, return addresses, and simple values the engine knows the size of.
  • The heap is a large, unstructured area for everything whose size can change or that must outlive a single call: objects, arrays, functions, closures, most strings, Maps and so on.

A variable that holds an object really holds a reference โ€” an arrow pointing into the heap. That's why assigning an object to a second variable doesn't copy it (Copying Objects covers the consequences).

JavaScript
let user = { name: "Ana" };  // object lives on the heap; `user` points to it
let admin = user;            // a second arrow to the SAME object
admin.name = "Bo";
user.name;                   // "Bo"

This is a mental model, not a rule. The language specification doesn't mention a stack or heap. Engines such as V8 (Chrome, Node.js), SpiderMonkey (Firefox) and JavaScriptCore (Safari) make their own choices: small integers may live directly in a variable slot, while a closure's variables may be moved to the heap so they survive after the call returns. The model is still the right way to think about references and lifetimes.

Reachability: how the garbage collector decides

The garbage collector (GC) doesn't know which objects you plan to use again. It uses a simpler, safe rule: an object stays alive as long as it's reachable.

The starting points are called roots. They include global variables, the variables of every function currently on the call stack, and things the browser holds onto, like registered event listeners and pending timers. Anything a root points to is reachable; anything those objects point to is reachable too, and so on.

Modern engines use a mark-and-sweep algorithm:

  1. Mark: start from the roots and follow every reference, marking each object reached.
  2. Sweep: every object left unmarked can't be reached by any code, so its memory is freed.

Because it follows references from the roots, mark-and-sweep handles cycles without trouble. Two objects pointing at each other but unreachable from any root are both collected.

Real engines add many refinements. They're generational (most objects die young, so new objects are checked often in a small "nursery" and survivors are checked rarely), incremental and concurrent (work is split up or done on other threads so your page doesn't freeze). You can't control when the GC runs, and you don't need to.

JS Reachable or garbage?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common memory leaks

A memory leak in JavaScript is memory you no longer need that stays reachable by accident. One leaked object rarely matters. A leak inside code that runs on every click, route change or timer tick adds up until the tab becomes sluggish or crashes. Here are the usual suspects.

1. Accidental globals and growing collections

Global variables are roots, so whatever they hold lives until the page closes. In strict mode (and in modules), assigning to an undeclared name throws instead of silently creating a global. The bigger danger today is a module-level Map, array or cache that only ever grows:

JavaScript
const seen = new Map();          // module-level = lives forever
function track(event) {
  seen.set(event.id, event);     // never removed โ†’ grows without limit
}

Give caches a maximum size, delete entries you're done with, or use a WeakMap keyed by objects so entries vanish when the key object does.

2. Forgotten timers

A running setInterval is a root. Its callback, and everything that callback's closure references, stays alive until you call clearInterval() โ€” even after the element it updates has been removed. Always keep the timer ID and clear it when the feature is closed (Timers).

3. Event listeners that are never removed

A listener attached to window, document or any long-lived element keeps its callback, and the callback's closure, alive. Components that add listeners when they open must remove them when they close. The cleanest way is an AbortController: pass its signal to every addEventListener call, then call abort() once to remove them all (AbortController).

4. Closures holding more than they need

A closure keeps its outer variables alive as long as the closure itself is alive. If a small callback refers to a variable that holds a huge array, the huge array stays too:

JavaScript
function setup(button) {
  const report = buildHugeReport();        // 50 MB of data
  const total = report.total;
  button.addEventListener("click", () => {
    console.log(total);                    // only uses a number...
    // ...but if it mentioned `report`, all 50 MB would stay alive
  });
}

Copy out just the pieces you need before creating long-lived callbacks.

5. Detached DOM elements

When you remove an element from the page, it isn't freed if JavaScript still holds a reference to it โ€” in an array, a cache, or a closure. The element, its children and their listeners all stay in memory as a detached tree.

Try the leak below. Each click on Open panel builds a panel with many rows and removes the previous one, but the leaky version also stores every panel in an array. Compare the counts:

Detached DOM and listener cleanup

The AbortController part matters too: without cleanup.abort(), every old panel would stay reachable through its resize listener on window, even with the array gone.

Finding leaks with DevTools

When a page gets slower the longer it stays open, measure before guessing:

  1. Open DevTools and go to the Memory panel (Chrome, Edge) or the Memory tool (Firefox).
  2. Take a heap snapshot.
  3. Repeat the suspicious action several times โ€” open and close a dialog, switch routes and come back.
  4. Take a second snapshot and choose the Comparison view. Objects whose count keeps growing are your suspects.
  5. Select one and read its retainers: the chain of references that keeps it alive. That chain points straight at the leaking array, listener or closure.

In Chrome, typing "Detached" in a snapshot's class filter lists detached DOM trees directly. The Performance panel's memory checkbox shows the heap size over time: a healthy page looks like a saw blade (grows, drops after each GC); a leaking page looks like a staircase that never comes back down.

Don't fear normal allocation. Creating lots of short-lived objects is fine โ€” that's exactly what generational GCs are optimized for. Only worry when memory keeps rising across repeated actions, or when profiling shows long GC pauses in a hot loop (JavaScript Performance).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When can the garbage collector free an object?

    Collection is based on reachability. Setting a variable to null only helps if that was the last reference.
  2. 2. Two objects reference each other, but nothing else references either of them. What happens?

    Mark-and-sweep only keeps what it can reach from the roots. An isolated cycle is never marked, so it's swept.
  3. 3. What causes RangeError: Maximum call stack size exceeded?

    Every call pushes an execution context on the call stack. Recursion without a working base case keeps pushing until the stack is full.
  4. 4. You remove an element with element.remove(), but an array still holds it. What is it called?

    The element left the document but is still reachable from JavaScript, so it and its whole subtree can't be freed.
  5. 5. Which change removes several event listeners in one step when a component closes?

    Listeners registered with a signal are removed automatically when that signal is aborted.

Summary

  • Each function call creates an execution context on the call stack; too much nesting throws a RangeError.
  • Think of small local data as living on the stack and objects on the heap; variables hold references to heap objects.
  • The garbage collector frees what is unreachable from the roots, using mark-and-sweep, so isolated cycles are fine.
  • Leaks are reachable leftovers: growing collections, forgotten timers, unremoved listeners, oversized closures and detached DOM trees.
  • Clean up with clearInterval(), AbortController, size limits and WeakMap, and confirm leaks with heap snapshot comparisons.

Next: Testing JavaScript โ€” prove your code works, and keep it working, with automated tests.