Skip to content
intermediatePhase 33 · Advanced JavaScript

Garbage Collection

Understand how JavaScript manages memory with mark-and-sweep GC.

30m
0 problems
Topic Progress0%

Mark and Sweep

Modern JavaScript engines use the mark and sweep algorithm for garbage collection.

How Mark and Sweep Works

  1. Mark Phase: Start from root objects (global, current stack) and mark all reachable objects
  2. Sweep Phase: Unmark all objects, delete unmarked (unreachable) objects
function createUser() {
  let user = { name: 'Alice' }; // Object created
  return user; // Returned, so it's reachable
}

let alice = createUser(); // alice references the object
// { name: 'Alice' } is reachable

alice = null; // Object is now unreachable
// Garbage collector will free this memory

Visual Example

Before GC:
┌─────────┐    ┌─────────┐
│ Global  │───→│ Object A │
└─────────┘    └─────────┘
     │              │
     ▼              ▼
┌─────────┐    ┌─────────┐
│ Object B │    │ Object C │ (unreachable)
└─────────┘    └─────────┘

After GC:
┌─────────┐    ┌─────────┐
│ Global  │───→│ Object A │
└─────────┘    └─────────┘
     │              │
     ▼              ▼
┌─────────┐
│ Object B │
└─────────┘
(Object C deleted)

Reachability

An object is reachable if:

  • Referenced by a variable in scope
  • Referenced by another reachable object
  • A DOM element referenced in JavaScript
let obj = { data: 'important' };

// Object is reachable
console.log(obj.data); // 'important'

// Remove reference
obj = null;
// Object is now unreachable, will be garbage collected

Reference Counting

Reference counting was used in older systems. An object is garbage collected when its reference count reaches zero.

How Reference Counting Works

let objA = { name: 'A' }; // Reference count: 1
let objB = { name: 'B' }; // Reference count: 1

// Circular reference
objA.ref = objB; // objB reference count: 2
objB.ref = objA; // objA reference count: 2

objA = null; // objA reference count: 1 (still referenced by objB)
objB = null; // Both reference counts: 0, both collected

The Circular Reference Problem

function createCycle() {
  let obj1 = {};
  let obj2 = {};
  
  // Circular reference
  obj1.ref = obj2;
  obj2.ref = obj1;
  
  // Both become unreachable when function returns
  // Reference counting can't handle this!
}

createCycle();
// With reference counting: memory leak!
// With mark and sweep: correctly collected

Modern Solution

// Modern engines use mark and sweep, not reference counting
// They can detect unreachable objects even with circular references

function demonstrate() {
  const obj1 = { data: 'A' };
  const obj2 = { data: 'B' };
  
  obj1.ref = obj2;
  obj2.ref = obj1;
  
  // When function returns, both are unreachable
  // Mark and sweep correctly collects them
}

demonstrate();
// Memory is freed correctly

When GC Runs

Garbage collection runs automatically but you can influence when it happens.

Automatic Collection

// GC runs when needed
function allocateMemory() {
  // Create many objects
  const arr = [];
  for (let i = 0; i < 1000000; i++) {
    arr.push({ index: i });
  }
  // arr goes out of scope, objects become unreachable
  // GC will collect them when needed
}

// GC decides when to run based on:
// - Memory usage
n// - Number of objects
// - Time since last collection

Factors Influencing GC

// 1. Memory pressure
// More allocations = more frequent GC

// 2. Heap size
// Engines have heap limits (usually 1-4GB)

// 3. Application state
// Idle time = more aggressive collection

// 4. Browser optimization
// Browsers batch GC during idle periods

Minimizing GC Impact

// BAD: Creates many objects
function processData() {
  for (let i = 0; i < 1000; i++) {
    const temp = { value: i }; // New object each iteration
    process(temp);
  }
}

// GOOD: Reuse objects
function processData() {
  const temp = { value: 0 };
  for (let i = 0; i < 1000; i++) {
    temp.value = i; // Reuse same object
    process(temp);
  }
}

// GOOD: Use object pools
const objectPool = [];
function getTemp() {
  return objectPool.pop() || {};
}
function releaseTemp(obj) {
  objectPool.push(obj);
}

Monitoring GC (Chrome DevTools)

// In Chrome DevTools:
// 1. Open Performance tab
// 2. Record a session
// 3. Look for GC events in the timeline

// Or use performance.memory (Chrome only)
console.log(performance.memory.usedJSHeapSize);
console.log(performance.memory.totalJSHeapSize);

Practice Problems

0/3solved
Build Garbage Collection Component

Create a reusable React component implementing Garbage Collection. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Garbage Collection Testing

Write unit and integration tests for Garbage Collection using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Garbage Collection Performance

Optimize Garbage Collection for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What is garbage collection?

Question 1 options

2. What algorithm do modern JS engines use?

Question 2 options

3. When does garbage collection run?

Question 3 options

4. What problem does mark and sweep solve that reference counting doesn't?

Question 4 options

Flashcards

Question

What is garbage collection?

Answer

Automatic memory management that identifies and frees unreachable objects.

Question

What is mark and sweep?

Answer

GC algorithm that marks reachable objects from roots, then sweeps (deletes) unmarked objects.

Question

What is a circular reference?

Answer

When two objects reference each other. Mark and sweep handles this; simple reference counting doesn't.

Question

How to reduce GC impact?

Answer

Reuse objects, use object pools, avoid creating many temporary objects in loops.

Question

What is Garbage Collection?

Answer

Garbage Collection is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.Garbage collection automatically frees unreachable objects
  • 2.Mark and sweep is the standard algorithm
  • 3.Circular references are handled by modern engines
  • 4.You can't force GC, but can minimize its impact
  • 5.Object reuse and pooling improve performance

Interview Tips

  • Explain mark and sweep algorithm clearly
  • Discuss circular references and how they're handled
  • Explain when and why garbage collection runs
  • Show how to reduce GC impact in code

Cheat Sheet

Garbage Collection Cheat Sheet

What is it?

Automatic memory management for unreachable objects.

Mark and Sweep Algorithm

  1. Mark: Mark all reachable objects from roots
  2. Sweep: Delete unmarked objects

Key Concepts

  • Object is unreachable = no references
  • Circular references handled by mark and sweep
  • GC runs automatically based on heuristics

Reducing GC Impact

  • Reuse objects
  • Use object pools
  • Avoid temporary objects in loops
  • Profile with Chrome DevTools