Chapter XIV · Heap & Memory

Garbage Collection

Garbage collection is the automated process by which the JavaScript engine cleans up memory by finding and removing unreachable objects.

01 How It Works

Think of a sanitation crew walking through a building throwing away items that have no owners attached.

Using algorithms like 'Mark-and-Sweep', the engine periodically checks root references to determine if objects can still be reached.

example.js
let obj = { name: "Temp" };
obj = null; // Original object is now unreachable and collected
  1. 1. Roots (global objects and active stack frames) are identified.

  2. 2. 'Mark-and-Sweep' traverses all reachable child references from roots.

  3. 3. Unmarked unreachable memory blocks are swept and reclaimed.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
function process() {
  let temporaryObj = { data: 123 };
  return temporaryObj.data;
}
process(); // temporaryObj is garbage collected after function execution completes.

Key Takeaway

Automated garbage collection prevents memory leaks by reclaiming unreferenced heap allocations.

Related Concepts