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

Understanding Comments in JavaScript for Beginners

Comments in JavaScript help you explain code and prevent mixing. They guide anyone who reads or edits your script. Understand…

JavaScript Math trunc: How to Removes Decimals

JavaScript gives you the Math.trunc() function to work with decimal numbers. You use it when you want to remove the…

JavaScript “use strict” Mode: What It Is and Why You Should Use It

Code mistakes used to slip by without a warning. That made bugs hard to trace and fix. JavaScript "use strict"…

JavaScript toSorted Function Guide with Examples

This guide shows how toSorted function works in JavaScript with arrays. It covers syntax, rules, and examples for numbers, text,…

JavaScript Optional Chaining “?”: How it Works with Examples

JavaScript optional chaining lets you access object values without runtime errors. It checks if a property exists before access and…

JavaScript Math tan: The Tangent of an Angle in Radians

JavaScript Math.tan() finds the tangent of an angle in radians. You use it when you need to solve angle-based math.…

forEach Loop in JavaScript: A Complete Guide with Examples

The forEach loop in JavaScript allows you to go through each item in an array. You do not have to…

JavaScript Math atan: Arc Tangent of a Number in Radians

Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…

String Operators in JavaScript: A Complete Guide to Concatenation

String Operators in JavaScript help you work with text. You can join, build, or change strings. Most of what you…

JavaScript math.exp: How to Calculate e^x

Math.exp is a built-in JavaScript function that returns the value of e raised to a given number. Here, e is…

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.