Glossary / Garbage collection basics

Garbage collection basics

JavaScript engines automatically reclaim memory for objects that are no longer reachable from live program roots. Garbage collection removes the need for explicit object deallocation in ordinary code, but it does not prevent memory leaks: references retained accidentally keep objects reachable and therefore ineligible for collection.

Reachability and resource lifetime

Roots include active execution state, global references, module state, closures, and host-managed references such as event listeners. If a long-lived callback closes over a component, then the component and objects reachable from it may remain alive. Generational, incremental, and concurrent strategies are common implementation techniques, but exact algorithms and collection timing are not guaranteed by ECMAScript.

WeakMap and WeakSet avoid keeping their keys/members alive solely through membership. They are appropriate for optional metadata and caches, not for deterministic lifecycle control. FinalizationRegistry callbacks may run late or not before shutdown. File handles, sockets, subscriptions, and timers need explicit close/dispose/clear operations; memory GC does not imply timely resource cleanup.

Performance and diagnostics

Allocation is often cheap; optimizing by pooling everything can increase complexity and retain memory. Use heap snapshots, allocation timelines, and retaining paths to diagnose growth. Distinguish temporary peak allocation from a leak by repeating workloads and observing post-GC retained heap. Avoid depending on manual garbage-collection hooks in production logic.

Interview questions

  1. When is an object collectible? When it is unreachable from live roots, subject to implementation timing.
  2. Does GC prevent leaks? No; reachable objects can be retained accidentally forever.
  3. Should GC close a socket? No; use explicit resource cleanup.
  4. Are GC algorithms specified? No; they are engine implementation details.

References