What is JavaScript garbage collection?

JavaScript automatically manages memory allocation and deallocation through a process called garbage collection. When you declare variables or create objects, JavaScript allocates memory for them. The garbage collector then identifies and frees memory that is no longer needed by your application.

How Garbage Collection Works

JavaScript's garbage collector runs automatically in the background, scanning memory to find objects that are no longer reachable or referenced by your code. When these "orphaned" objects are found, their memory is freed up for reuse.

Mark-and-Sweep Algorithm

The most common garbage collection algorithm in modern JavaScript engines is the mark-and-sweep algorithm:

function createObjects() {
    let obj1 = { name: "Object 1" };
    let obj2 = { name: "Object 2", ref: obj1 };
    
    console.log("Objects created:", obj1.name, obj2.name);
    
    // obj1 and obj2 will be marked as reachable while function runs
    return obj2; // Only obj2 remains reachable after function ends
}

let result = createObjects();
console.log("Returned object:", result.name);

// obj1 is still reachable through result.ref
console.log("Referenced object:", result.ref.name);
Objects created: Object 1 Object 2
Returned object: Object 2
Referenced object: Object 1

Reference-Counting Garbage Collection

An older approach that counts references to each object. When an object's reference count reaches zero, it becomes eligible for garbage collection:

let obj = { data: "Important data" }; // Reference count: 1
let anotherRef = obj;                  // Reference count: 2

console.log("Object data:", obj.data);

obj = null;        // Reference count: 1 (anotherRef still points to it)
anotherRef = null; // Reference count: 0 (eligible for garbage collection)

console.log("References cleared");
Object data: Important data
References cleared

Common Scenarios

Here are typical situations where garbage collection occurs:

// Scenario 1: Variables going out of scope
function temporaryFunction() {
    let tempVar = "This will be garbage collected";
    console.log(tempVar);
} // tempVar becomes unreachable after function ends

temporaryFunction();

// Scenario 2: Reassigning variables
let myVar = { type: "original" };
console.log("Before:", myVar.type);

myVar = { type: "new" }; // Original object becomes unreachable
console.log("After:", myVar.type);

// Scenario 3: Clearing references
let dataArray = [1, 2, 3, 4, 5];
console.log("Array length:", dataArray.length);

dataArray = null; // Array becomes eligible for garbage collection
console.log("Array cleared");
This will be garbage collected
Before: original
After: new
Array length: 5
Array cleared

Memory Management Best Practices

While garbage collection is automatic, you can help optimize memory usage:

  • Set large objects to null when no longer needed
  • Avoid creating unnecessary global variables
  • Remove event listeners when components are destroyed
  • Clear intervals and timeouts when done

Conclusion

JavaScript's automatic garbage collection uses algorithms like mark-and-sweep to free unused memory. Understanding how it works helps you write more memory-efficient code, though the process itself requires no manual intervention.

Updated on: 2026-03-15T23:18:59+05:30

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements