Garbage Collection in JavaScript (original) (raw)

Last Updated : 17 Feb, 2025

In JavaScript, Garbage Collection (GC) is an automatic memory management feature that helps free up memory that is no longer needed by a program. JavaScript uses a garbage collector to identify and remove unused objects, ensuring efficient memory usage and preventing memory leaks.

What is Garbage collection?

Garbage collection refers to the process of automatically reclaiming memory occupied by objects that are no longer accessible. Since JavaScript manages memory allocation dynamically, developers don’t need to manually allocate or free memory like in low-level languages (e.g., C, C++).

How Garbage Collection works in JavaScript?

Algorithm behind Garbage collection(Mark and Sweep)

The Mark-and-Sweep Garbage Collection algorithm helps manage memory by identifying and removing unused objects in JavaScript. This code simulates the process where objects are marked as reachable and then swept away if they are no longer needed.

JavaScript `

class algo { constructor() { this.objects = []; }

createObject(name) {
    const obj = { name: name, refCount: 1 };
    this.objects.push(obj);
    return obj;
}

mark() {
    this.objects.forEach(obj => {
        if (obj.refCount > 0) {
            obj.marked = true;
        }
    });
}

sweep() {
    this.objects = this.objects.filter(obj => obj.marked);
}

collectGarbage() {
    this.mark();
    this.sweep();
}
prints() {
    return this.objects
}

} const gc = new algo();

const obj1 = gc.createObject("Object 1"); const obj2 = gc.createObject("Object 2");

obj2.refCount = 0;

gc.collectGarbage(); console.log(gc.prints())

`

Output

[ { name: 'Object 1', refCount: 1, marked: true } ]

Why is Garbage Collection Important?

Use Cases of Garbage Collection in JavaScript

1. Unreachable Object Gets Collected

This JavaScript code demonstrates how objects are referenced by variables and how setting a variable to null can make an object eligible for garbage collection. It highlights the concept of memory management when objects become unreachable.

JavaScript `

let obj1 = { name: "Object 1" }; let obj2 = { name: "Object 2" }; obj1 = null; console.log(obj1)

`

2. Garbage Collection after Removing References

This code demonstrates how setting a variable to null removes the reference to an object, making it eligible for garbage collection. The object that was previously referenced is no longer accessible.

JavaScript `

let user = { name: "Pranjal" } user = null console.log(user)

`

3. Removing Array Elements

This code demonstrates how to remove an element from an array using the splice() method. In this case, the first element of the array is removed.

JavaScript `

let a = [1, 2, 3, 4] a.splice(0, 1) console.log(a)

`

4. Function Creating Objects and Removing Them

This code shows how an object is created within a function and goes out of scope once the function finishes. The object becomes eligible for garbage collection since there are no external references to it.

JavaScript `

function createObj() { let temp = { id: 1 }; }

createObj(); console.log(temp)

`

5. Memory Cleanup after Setting to Null

This code demonstrates how setting an object to null removes the reference to the object, making it eligible for garbage collection. After this, the object is no longer accessible.

JavaScript `

let data = { name: "Test" }; data = null; console.log(data)

`

Advantages of Garbage Collection in JavaScript

Best Practices for Efficient Garbage Collection

Conclusion

Garbage collection in JavaScript simplifies memory management by automatically removing unused objects, preventing memory leaks, and optimizing performance. This reduces development complexity, allowing developers to focus on functionality rather than manual memory handling.