Full Byte Developer.

Garbage collection: mark-and-sweep in plain words

GC frees unreachable objects from roots via mark-and-sweep; circular refs need tracing, not reference counts.

Published here , updated · 6 sources

Manual free is easy to get wrong. Garbage collection (GC) watches allocations and reclaims memory that the program cannot reach anymore [1] [2]. Pair this with stack vs heap memory: the heap is where long-lived objects usually live; GC is how many managed runtimes clean that heap.

Quick start (under a minute)

Open a JavaScript console (browser devtools or Node). Run:

javascript
let kept = { tag: "root-linked" };
let temp = { tag: "dropped" };
temp = null;

You should see no error [1]. The { tag: "dropped" } object becomes unreachable after temp = null because only temp pointed at it. A future collection may reclaim it; consoles do not print a "freed" line by default [1] [3].

Reachability decides what stays alive

MDN frames GC as approximating an undecidable problem: deciding whether memory is still needed in the general case [1]. Collectors therefore define a narrower rule. Mark-and-sweep uses reachability from a set of roots [1] [3].

Roots include the running function's locals and parameters, callers further up the stack, and globals [3]. Anything you can walk to from a root by following references stays. Everything else is garbage.

Mark-and-sweep as a teaching picture

Real engines add write barriers, generations, and concurrent marking [4]. The mark/sweep split still explains why dropping the last external pointer matters [1] [3].

SpiderMonkey's hybrid collector can run marking work in parallel slices across cores [4]. That is why the same JavaScript snippet may pause for a different wall-clock duration in Firefox versus Node: the algorithm is reachability, the scheduler is vendor-specific.

Worked example: orphan an object

js
let root = { name: "alive" };
let orphan = { name: "gone soon" };
orphan = null;
// After this assignment, nothing reaches the { name: "gone soon" } object.

In Node 20 on this host (2026-12-03), you can prove the program still runs and root remains usable:

bash
node -e 'let root={name:"alive"}; let orphan={name:"gone"}; orphan=null; console.log(root.name);'

Observed:

text
alive

No leak message appears because collection is asynchronous [1]. DevTools Memory snapshots in a browser show retained graphs when you forget globals; this snippet is the minimal reachability lesson.

See why mark-and-sweep beats naive reference counts

Reference counting frees an object when its pointer count hits zero. MDN notes the circular-reference failure: two objects that only point at each other keep non-zero counts forever, even after the function that created them returns [1].

js
function cycle() {
  const a = {};
  const b = {};
  a.other = b;
  b.other = a;
}
cycle();

Run:

bash
node -e 'function cycle(){const a={};const b={};a.other=b;b.other=a;} cycle(); console.log("cycle complete");'

Observed:

text
cycle complete

After cycle() returns, a and b are unreachable from roots, but each would still show reference count 1 under naive counting [1]. Mark-and-sweep marks every object reachable from roots, then sweeps unmarked objects [1] [3]. Cycles without a path from a root are collected. MDN states modern JavaScript engines no longer use reference counting as their GC algorithm [1].

Watch the collector work in slices when engines allow it

A full stop-the-world pass can hitch a UI thread. SpiderMonkey's docs describe a hybrid tracing collector that is precise, incremental, generational, partially concurrent, parallel, and compacting [4]. Incremental collection breaks work into slices so JavaScript can run between them; not every phase can be incremental [4].

That detail is engine-specific. V8, JavaScriptCore, and SpiderMonkey share the reachability idea with different schedulers. Do not invent pause milliseconds without measuring on a named engine, version, and hardware.

Retention beats algorithm choice

GC cannot save you from retaining large graphs through a global cache, a forgotten listener, or a closure that still points at a huge structure [1] [3]. The event loop keeps callbacks alive until you remove them (JavaScript promises and the event loop). Drop the last reference you control when the work is done. Then let the collector reclaim.

WeakMap and WeakRef exist for specialized lifetime patterns; read MDN before using them as a default architecture [1].

Compaction moves live objects to reduce heap fragmentation in engines that support it [4]. You rarely observe compaction directly in JavaScript; you observe shorter pauses or lower RSS after long sessions. Treat that as background engineering, not something to tune from application code without vendor flags.

In the browser, DevTools Memory timeline shows allocation peaks and retained object graphs after you take a heap snapshot [1]. Use it when a tab grows without bound: search for detached DOM trees and event listeners before you blame the collector algorithm. Record one snapshot before and after a suspected leak path; retained size deltas beat guessing which microtask "felt" expensive.

Other managed runtimes reuse the same reachability idea with different schedulers. Java's HotSpot and .NET's GC are tracing collectors with generational tuning; Python combines reference counting for most objects with a cycle detector for ref cycles [1]. The lesson carries: roots define live, collectors reclaim the rest.

More reader questions

What is the generational hypothesis? Most objects die young [4]. Engines collect nursery heaps often and old heaps rarely. That cuts average pause cost without changing the reachability rule.

Can I force GC in production? Only on some debug builds [1]. Fix dangling references and listeners instead of scheduling gc() in hot paths.

Retention graphs beat algorithm folklore: a forgotten event listener keeps a whole subtree alive while the collector runs on schedule. Take one heap snapshot before you rewrite a hot path for a "faster GC."

Failure modes worth naming

Blaming "the GC" for every stutter without a heap snapshot. Measure retained size and listener counts first [1].

Expecting delete obj.prop to free nested graphs instantly. Deleting a property removes one edge; other roots may still hold the child [3].

Circular structures always leak in JavaScript. Tracing collectors handle pure cycles once nothing roots them [1].

Thinking stack variables and heap objects share one GC rule. Locals hold references; when a frame pops, those references vanish from roots unless escaped to the heap [1] (stack vs heap).

Forcing window.gc() in Chrome with flags and calling it a fix. Diagnostics tool, not production hygiene [1].

GC does not remove lifetime thinking in FFI or workers. Cross-boundary ownership still matters when C++, Rust, or WASM shares pointers.

Before you blame "the GC" for a stutter, take one heap snapshot and search for retained listeners or detached DOM. Finalizers and WeakRef callbacks run after collection decisions; they do not replace close() on host resources [1]. How the main thread schedules work around pauses is covered in JavaScript promises and the event loop quick start; Python's different threading story is Python GIL: why threads are not truly parallel.

Send this to the friend who blames the GC without taking one heap snapshot.

Illustration of a rooted teal object graph of cubes and disks with orange rings above a purple debris field of unused cubes and dust, no people and no readable UI text.
Live objects stay linked from roots; unreachable debris sits below for reclaim.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

Does JavaScript still use reference counting as its main GC?

MDN's memory management guide says no modern JavaScript engine uses reference counting for garbage collection anymore. Engines use tracing collectors based on reachability.

Why do circular references break naive reference counting?

If two objects point at each other and nothing else reaches them, each still has a non-zero reference count. Mark-and-sweep treats them as garbage because they are unreachable from roots.

What are roots?

Roots are values the collector always starts from, such as the currently executing function's locals, callers on the stack, and global variables. MDN and javascript.info both use that framing.

Is GC free?

No. Collectors trade CPU time and pauses for automatic free. SpiderMonkey docs describe incremental and concurrent work specifically to reduce long stop-the-world pauses.

When does an object actually disappear?

After a collection when no root path references it. Timing is engine-specific; do not rely on immediate free after dropping the last variable [1] [3].

Sources

Next in this stack