🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

Memory Management

AI & DATA SCIENCE // memory-management

JavaScript uses automatic garbage collection. Memory leaks occur when references to unused objects are accidentally retained.

Syntax

// Manual memory cleanup
function cleanup() {
  element.removeEventListener('click', handler);
  largeCache = null; // allow GC
}

Deep Dive Course

JavaScript's **garbage collector** (GC) uses **mark-and-sweep** — periodically marking all reachable objects from roots (global, active stack), and sweeping (freeing) everything else. **Memory leaks** happen when you unintentionally retain references: forgotten event listeners, growing caches, circular references in older engines.

1Understanding Memory Management

JavaScript's garbage collector (GC) uses mark-and-sweep — periodically marking all reachable objects from roots (global, active stack), and sweeping (freeing) everything else. Memory leaks happen when you unintentionally retain references: forgotten event listeners, growing caches, circular references in older engines.

💡

Use Chrome DevTools Memory tab to take heap snapshots before and after operations to find leaks.

editor.html
// Memory leak: event listener not removed
function addHandler() {
  const heavyObj = new Array(1000000).fill('data');
  document.addEventListener('click', () => {
    console.log(heavyObj.length); // heavyObj can't be GC'd!
  });
}

// Fix: remove listener
function addHandlerFixed() {
  const heavyObj = new Array(1000000).fill('data');
  function handler() { console.log(heavyObj.length); }
  document.addEventListener('click', handler);
  return () => document.removeEventListener('click', handler);
}
localhost:3000

2Practical Example

Here is a real-world application of Memory Management showing how it is used in production JavaScript code.

editor.html
// WeakMap: keys don't prevent GC
const cache = new WeakMap();

function getCachedData(obj) {
  if (cache.has(obj)) return cache.get(obj);
  const data = expensiveCompute(obj);
  cache.set(obj, data); // when obj is GC'd, so is its cache entry
  return data;
}
localhost:3000

3Best Practices

Follow these guidelines when working with Memory Management:

1. Remove event listeners when components unmount

2. Nullify references to large objects when done

3. Use WeakMap/WeakSet for cache keys that shouldn't prevent GC

⚠️

Tip: Use Chrome DevTools Memory tab to take heap snapshots before and after operations to find leaks.

editor.html
// Memory leak: event listener not removed
function addHandler() {
  const heavyObj = new Array(1000000).fill('data');
  document.addEventListener('click', () => {
    console.log(heavyObj.length); // heavyObj can't be GC'd!
  });
}

// Fix: remove listener
function addHandlerFixed() {
  const heavyObj = new Array(1000000).fill('data');
  function handler() { console.log(heavyObj.length); }
  document.addEventListener('click', handler);
  return () => document.removeEventListener('click', handler);
}
localhost:3000

Examples

Example 01Basic Usage
// Memory leak: event listener not removed
function addHandler() {
  const heavyObj = new Array(1000000).fill('data');
  document.addEventListener('click', () => {
    console.log(heavyObj.length); // heavyObj can't be GC'd!
  });
}

// Fix: remove listener
function addHandlerFixed() {
  const heavyObj = new Array(1000000).fill('data');
  function handler() { console.log(heavyObj.length); }
  document.addEventListener('click', handler);
  return () => document.removeEventListener('click', handler);
}
Example 02Advanced Example
// WeakMap: keys don't prevent GC
const cache = new WeakMap();

function getCachedData(obj) {
  if (cache.has(obj)) return cache.get(obj);
  const data = expensiveCompute(obj);
  cache.set(obj, data); // when obj is GC'd, so is its cache entry
  return data;
}

Best Practices

  • Remove event listeners when components unmount
  • Nullify references to large objects when done
  • Use WeakMap/WeakSet for cache keys that shouldn't prevent GC

Interview Question

What are common causes of memory leaks in JavaScript?

Hint: Unintentionally retained references.

1. Forgotten event listeners — listeners keep a reference to the handler's closure. 2. Detached DOM nodes referenced in JS. 3. Closures capturing large objects unnecessarily. 4. Global variables accumulating data. 5. setInterval/setTimeout not cleared. 6. Growing caches with no eviction policy.

Exercises

MediumPractice using Memory Management in a real scenario.
View Solution
// Memory leak: event listener not removed
function addHandler() {
  const heavyObj = new Array(1000000).fill('data');
  document.addEventListener('click', () => {
    console.log(heavyObj.length); // heavyObj can't be GC'd!
  });
}

// Fix: remove listener
function addHandlerFixed() {
  const heavyObj = new Array(1000000).fill('data');
  function handler() { console.log(heavyObj.length); }
  document.addEventListener('click', handler);
  return () => document.removeEventListener('click', handler);
}

Frequently Asked Questions

What are common causes of memory leaks in JavaScript?

1. Forgotten event listeners — listeners keep a reference to the handler's closure. 2. Detached DOM nodes referenced in JS. 3. Closures capturing large objects unnecessarily. 4. Global variables accumulating data. 5. setInterval/setTimeout not cleared. 6. Growing caches with no eviction policy.

Related Functions

ClosuresEvent-ListenersScope-ContextCallback-Functions