Have you heard about Hack Frontend Community?Join us on Telegram!
Practice JS Problems

JavaScript Garbage Collector: Mark-and-Sweep Explained

Garbage Collector is a built-in mechanism in JavaScript that automatically manages memory. It's responsible for freeing memory occupied by objects that are no longer used in the program.

You don't manage memory manually — JavaScript engine does it for you (e.g., V8 in Chrome/Node.js).

How Does Garbage Collector Work?

JavaScript allocates memory for variables and objects when they're created, and frees it when they're no longer reachable.

Main principle:

Object is considered "garbage" if there are no more references to it.

Example:

let user = { name: "Alice" };
user = null; // Now object can be deleted from memory

Algorithms Used in GC

Mark-and-Sweep

Most common algorithm:

  • Marks all objects accessible through variables (root objects).
  • All other objects are deleted as "garbage".

In this example object C is unreachable and will be deleted.

Reference Counting

Each object stores a number showing how many references point to it. If counter = 0, object is deleted.

Disadvantage: circular references aren't deleted.

let a = {};
let b = {};
a.ref = b;
b.ref = a;

// Both variables are null, but objects still reference each other
a = null;
b = null; // Potential memory leak!

How to Avoid Memory Leaks?

  • Remove unused timers: clearInterval, clearTimeout
  • Clear subscriptions, event handlers
  • Nullify large objects and DOM references: ref.current = null
  • Avoid global variables
  • Use WeakMap, WeakSet — they don't prevent garbage collection

Signs of Memory Leaks

  • Constant memory growth during use
  • Delays, freezes, lags
  • High RAM consumption in DevTools → Performance/Memory tab

Important:

Garbage collection in JavaScript is not instant — it's a process that runs periodically. So memory freeing can happen with delay.

Practice JS Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.