DEV Community

Cover image for JavaScript Garbage Collection
Kiran
Kiran

Posted on

JavaScript Garbage Collection

๐Ÿง  JavaScript Garbage Collection โ€” Explained Simply โ™ป๏ธ

Memory management in JavaScript is automatic.

You create objects โ†’ JavaScript allocates memory
Unused objects โ†’ Garbage Collector removes them

๐Ÿ‘‰ Developers donโ€™t manually free memory like C/C++


โšก What is Garbage Collection?

Garbage Collection (GC) is the process of automatically removing unused memory.

Goal:

โœ” Prevent memory leaks
โœ” Free unused objects
โœ” Optimize memory usage


๐Ÿงฉ Simple Example

let user = {
  name: "Kiran"
};

user = null;
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Original object now has no reference
๐Ÿ‘‰ Garbage Collector can remove it โœ…


๐Ÿง  How JavaScript Knows Memory is Unused

JavaScript mainly uses:

๐Ÿ‘‰ Mark-and-Sweep Algorithm


๐Ÿ” Step 1: Mark

GC starts from root references:

  • Global variables
  • Current function variables
  • Active closures

Anything reachable is marked as โ€œin useโ€.


๐Ÿงน Step 2: Sweep

Unreachable objects are removed from memory.


โšก Example

function test() {
  let data = { value: 10 };
}

test();
Enter fullscreen mode Exit fullscreen mode

After function ends:

๐Ÿ‘‰ data becomes unreachable
๐Ÿ‘‰ GC removes it


๐Ÿšจ Memory Leak Example

let cache = [];

function addData() {
  cache.push(new Array(1000000));
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ References are never removed
๐Ÿ‘‰ Memory keeps growing ๐Ÿšจ


๐Ÿง  Common Causes of Memory Leaks

โŒ Unremoved event listeners
โŒ Timers (setInterval)
โŒ Large global variables
โŒ Closures holding references
โŒ Detached DOM nodes


โš›๏ธ Real Use in React

Common leaks:

useEffect(() => {
  const timer = setInterval(() => {}, 1000);

  return () => clearInterval(timer);
}, []);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Cleanup prevents leaks โœ…


๐Ÿšจ Interview Trap

โŒ โ€œJavaScript developers donโ€™t care about memoryโ€
โœ” GC is automatic, but memory leaks still happen


๐Ÿ’ก Senior-Level Insight

Garbage collection improves developer experience,
but:

๐Ÿ‘‰ Too many allocations = GC pressure
๐Ÿ‘‰ Frequent GC pauses can affect performance

Real optimization = fewer unnecessary objects.


๐ŸŽฏ Interview One-Liner

JavaScript garbage collection is an automatic memory management process that removes objects no longer reachable in memory using algorithms like mark-and-sweep.


JavaScript #Frontend #WebDevelopment #GarbageCollection #Performance #ReactJS #InterviewPrep #EngineeringMindset

Top comments (0)