How does garbage collection work in JavaScript?

Understand how JavaScript automatically frees memory using reachability and reference checks.

advancedAdvanced conceptsjavascriptmemorygarbage collection
Published: 11/3/2025
Updated: 11/3/2025

Question

How does garbage collection work in JavaScript?


Answer

JavaScript has automatic garbage collection.
It uses a reachability model — if an object is no longer reachable from the root (like window or the global scope), it becomes garbage and is eligible for cleanup.

let user = { name: 'Ghazi' };
user = null; // object is no longer referenced → can be collected

Modern JS engines (V8, SpiderMonkey) use mark-and-sweep:

  1. Start from roots
  2. Mark all reachable objects
  3. Sweep unmarked ones

Real-World Example

Memory leaks often happen when we keep references in:

  • global variables
  • long-lived closures
  • DOM elements not removed from code

Quick Practice

Create an object, reference it in an array, then remove all references and explain when it becomes collectible.

Summary

GC in JS is automatic but not magic — your job is to avoid holding unnecessary references.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

Can I manually force garbage collection?

In browsers, no. JavaScript engines decide when to collect. In Node, there is a debug flag, but you shouldn’t rely on it.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.