JavaScript Garbage Collection: How it Works with Examples

javascript garbage collection

JavaScript removes unused memory blocks with garbage collection. It frees memory space so programs run without leaks.

What is JavaScript Garbage Collection

Garbage collection is a process that frees memory from unused objects. The engine runs this task and reclaims memory that no code references.

You do not call garbage collection directly in JavaScript. The engine handles this task by itself.

Here is an example:

// JavaScript has no direct syntax for garbage collection
let x = { value: 50 }
x = null

This sets the object to null. The engine may free the memory later, but the exact timing is not guaranteed.

Without garbage collection, unused objects would keep memory occupied. Over time, this could exhaust available memory and cause performance issues or program termination.

Modern engines use Mark-and-Sweep as the core garbage collection algorithm. Other techniques, like Generational Collection and Incremental Collection, are optimizations that make Mark-and-Sweep faster and reduce pauses.

Reference Counting is a historical method, not used anymore in JavaScript.

Types of Garbage Collection Algorithms

Reference Counting

Early engines freed objects once no variable pointed to them. Modern JavaScript engines no longer use this method because it fails with circular references. Today, engines rely on Mark-and-Sweep instead.

let obj = { data: "text" }
let ref = obj
obj = null
ref = null

Here, both variables point to the object. Once both become null the engine frees memory.

Mark and Sweep

This algorithm marks objects that remain in use. It then sweeps out those that no longer connect to the root object.

function sample() {
  let temp = { name: "user" }
}
sample()

The function runs and ends. The variable no longer connects to the root. The engine sweeps the memory.

Generational Collection

This method divides memory into young and old objects. The engine frees young ones more often because they expire faster.

let a = { id: 1 }
let b = { id: 2 }
// short lived
a = null

The engine clears a faster because it belongs to the young space.

Incremental Collection

This algorithm splits the collection into small steps. The engine runs each step in parts, so code execution does not pause too long.

let data = { count: 0 }
for (let i = 0; i < 100; i++) {
  data = { count: i }
}

The loop updates the object many times. The engine collects old copies step by step.

Examples

Remove Reference to Free Memory:

let user = { name: "Ali" }
user = null

This sets the object to null. The engine no longer finds references and frees the memory.

Function Scope Clears Memory:

function test() {
  let msg = { text: "Hello" }
}
test()

The variable lives inside the function. Once the function ends, the variable disappears, and the memory is cleared.

Circular References:

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

Both objects reference each other, but this does not cause a memory leak in modern engines. Mark-and-Sweep detects cycles and removes them once they become unreachable from the root (like the global object).

Loop Creates Short-Lived Objects:

for (let i = 0; i < 5; i++) {
  let temp = { num: i }
}

The loop creates objects that only live inside one cycle. Each object frees once the loop continues, and the engine reclaims space.

Wrapping Up

You learned what garbage collection does in JavaScript and how algorithms work.

Here is a quick recap:

  • Garbage collection helps you to free memory automatically.
  • Reference Counting was an early garbage collection algorithm, but modern JavaScript engines no longer use it because it fails with circular references.
  • Generational is a garbage collection algorithm that separates objects by age for faster memory cleanup.
  • Incremental is a garbage collection algorithm that splits work into small steps to reduce pause times.
  • Memory clears when objects cannot be reached from the root, even with circular references.
  • Functions and loops often create short-lived objects that are freed.

FAQs

What is JavaScript Garbage Collection?

JavaScript Garbage Collection frees memory from objects not used anymore.
  • It tracks objects in use
  • Removes unreachable objects
  • Releases memory automatically

How does JavaScript Garbage Collection work?

It works on the reachability concept.
  1. Variables referenced are reachable
  2. Objects linked to reachable variables stay
  3. Unreachable objects get deleted

// Example
let user = { name: "Tom" };
user = null; // object becomes unreachable

What are common types of JavaScript Garbage Collection?

  • Mark and Sweep: Finds and removes unused objects
  • Reference Counting: Deletes when no references exist

// Example of unused object
function test() {
  let temp = { a: 1 };
  return null;
}
// temp object will be collected

How to prevent memory leaks in JavaScript?

  • Remove unused event listeners
  • Clear intervals and timeouts
  • Set unused variables to null

// Example of cleanup
let timer = setInterval(() => console.log("run"), 1000);
clearInterval(timer); // prevents leak

Similar Reads

JavaScript Introduction: What is JavaScript?

The current essay is devoted to the basic principles and introduction of JavaScript. This language no longer needs to be…

JavaScript with Function Guide: Syntax with Examples

JavaScript has a statement called "with" that changes how code accesses object properties. The"with" Function makes a temporary scope, so…

Bitwise Operators in JavaScript

Bitwise operators work with binary data at the bit level in JavaScript. They process numbers in binary form and return…

JavaScript toSpliced Function Explained with Examples

The toSpliced function creates a new array without changing the original array in JavaScript. It returns a copy with new…

Understanding JavaScript Objects with Examples

JavaScript Objects hold values as key and value pairs, and they help you store and access data. Understand the JavaScript…

Understanding Data Types and Conversion in JavaScript

JavaScript works with different kinds of values. Each value has a type, known as a data type. These types help…

JavaScript Hello World: Write a Simple Program in 3 Ways

If you are ready to take your first steps into the realm of web development, then there cannot be a…

JavaScript toReversed Function with Examples

JavaScript toReversed returns a new array with the reversed order of its elements. It does not change the original array…

JavaScript for Loop: How to Iterate Arrays by Examples

JavaScript runs code in different ways, but the for loop stays one of the most common tools. You use it…

JavaScript While Loop: How It Works with Examples

The JavaScript while loop runs code as long as a condition stays true. You can use it to repeat tasks…

Previous Article

Git Help Command: A Complete Tutorial for Beginners

Next Article

HTML Element: Everything You Need To Know with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.