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.
// 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);
}2Practical Example
Here is a real-world application of Memory Management showing how it is used in production JavaScript code.
// 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;
}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.
// 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);
}