Table of Content
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 = nullThis 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 = nullHere, 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 = nullThe 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 = nullThis 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 = nullBoth 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?
- It tracks objects in use
- Removes unreachable objects
- Releases memory automatically
How does JavaScript Garbage Collection work?
- Variables referenced are reachable
- Objects linked to reachable variables stay
- 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 Ninja Code points to ways that help a person write code that runs fast and stays easy to read.…
JavaScript gives you several ways to round numbers, but not all of them round the same way. If you want…
JavaScript toReversed returns a new array with the reversed order of its elements. It does not change the original array…
JavaScript Math.log() was added to help people find the natural log of a number. It solves real problems in science…
JavaScript includes Math.sign to find out if a number is positive. It also helps detect negative values or zero. It…
Some numbers do not stay whole. You get decimal parts when you divide or calculate prices. You may need to…
The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…
The JavaScript nullish coalescing operator (??) gives a default value when a variable is null or undefined. Understand the Nullish…
JavaScript object methods are simple ways to handle data inside objects. An object can hold many values, and methods give…
The Math.acos function finds the angle in radians from a cosine value in JavaScript. It gives a value between 0…