How Garbage Collection Works in JavaScript?

Shweta Jain
3 min readOct 2, 2024

The JavaScript garbage collector automatically frees up memory when it detects that an object is no longer needed. Here’s a basic explanation using examples.

Example 1: Simple Variable Reassignment

let x = { name: "Alice" }; // Step 1: An object is created and assigned to 'x'
x = null; // Step 2: The reference to the object is removed

Explanation:

  1. When x is created, memory is allocated for the object { name: “Alice” }.
  2. When x is set to null, the reference to the object is lost.
  3. Since there are no other references to the object, the garbage collector marks the object as unreachable and will eventually free its memory.

Example 2: Nested Objects and Garbage Collection

function createObject() {
let person = {
name: "Bob",
address: {
city: "New York"
}
};
return person;
}

let person1 = createObject(); // Step 1: 'person1' holds a reference to the object
person1 = null; // Step 2: The reference is removed

Explanation:

  1. The createObject function creates an object person with a nested object address.
  2. person1 is assigned the object returned from createObject, so it holds a reference to it.

--

--

Shweta Jain
Shweta Jain

No responses yet