Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JS Puzzles · Const

Garbage Collection

JavaScript automatically reclaims objects that are no longer reachable from roots. The page explains reachability and the mark-and-sweep algorithm, including how cycles can be collected.

How it works

JavaScript automatically reclaims objects that can no longer be reached from any root, such as global variables or currently executing functions. The usual mark-and-sweep process marks roots and everything reachable through them, then removes unmarked objects. Cycles are handled because reachability, not merely reference counting, determines whether objects remain.

Key points

  • A garbage collector runs in the background and manages objects automatically.
  • Objects that cannot be reached through live references become eligible for reclamation.
  • The standard conceptual algorithm is mark-and-sweep.
  • Collection starts by marking roots, such as global state and active execution contexts.
  • The collector follows references outward from marked roots.
  • Tracking visited objects prevents repeated traversal.

Common mistakes

  • Garbage collection runs automatically; JavaScript provides no general way to force it or disable it.
  • An object can still be referenced by another unreachable object, yet the whole group can be collected.
  • Only objects reachable from the roots are marked and retained; unmarked objects are eligible for removal.

Example: Making an object unreachable

let user = { name: "Alice" };

user = null; // The object is no longer reachable

// The garbage collector can reclaim the object automatically.

After the only reference to the object is removed, the object becomes unreachable and may later be reclaimed automatically.

When to use it

Managing object lifetime

Release references to completed application data so it can become collectible.

Investigating memory leaks

Diagnose memory retention by tracing references from long-lived roots.

Reasoning about cycles

Understand why cyclic object references do not necessarily leak memory.

  • Reachability
  • Mark-and-sweep
  • Roots
  • Memory management

Source: Garbage collection. Checked 2026-10-15.