Memory Management & Garbage Collection
📖 Concept
JavaScript automatically manages memory through Garbage Collection (GC). However, understanding how it works prevents memory leaks and performance issues.
Memory lifecycle:
- Allocate — When you create variables, objects, functions
- Use — Read/write to the allocated memory
- Release — GC reclaims memory no longer reachable
GC Algorithm: Modern engines use Mark-and-Sweep — starting from "roots" (global object, call stack), it marks all reachable objects and sweeps (frees) unreachable ones.
Memory Leak — When memory that's no longer needed is not released because a reference still exists.
🏠 Real-world analogy: GC is like a janitor who cleans up meeting rooms. If a room has no one in it and no one is planning to use it (no references), it gets cleaned. But if someone left their notebook (dangling reference), the janitor can't clean that room.
💻 Code Example
1// Common memory leak: forgotten event listeners2function setupHandler() {3 const largeData = new Array(1000000).fill("x");4 document.addEventListener("click", () => {5 console.log(largeData.length); // largeData stuck in memory!6 });7}8// Fix: clean up listeners9function setupHandlerFixed() {10 const largeData = new Array(1000000).fill("x");11 const handler = () => console.log(largeData.length);12 document.addEventListener("click", handler);13 return () => document.removeEventListener("click", handler);14}15const cleanup = setupHandlerFixed();16// Later: cleanup();1718// Memory leak: closures retaining large scopes19function processData() {20 const hugeArray = new Array(1000000).fill("data");21 const processed = hugeArray.map(x => x.toUpperCase());22 return function getStats() {23 return processed.length; // Only needs length, but retains entire 'processed'24 };25}26// Fix: capture only what you need27function processDataFixed() {28 const hugeArray = new Array(1000000).fill("data");29 const length = hugeArray.length; // Capture just the length30 return function getStats() {31 return length; // hugeArray can be GC'd32 };33}3435// Memory leak: forgotten timers36function startPolling() {37 const data = loadLargeData();38 setInterval(() => {39 console.log(data);40 }, 5000); // Never cleared! data stuck in memory41}4243// WeakRef for cache that allows GC44let cache = new WeakRef(createExpensiveObject());45function getCached() {46 let obj = cache.deref();47 if (!obj) {48 obj = createExpensiveObject();49 cache = new WeakRef(obj);50 }51 return obj;52}
🏋️ Practice Exercise
Mini Exercise:
- Identify and fix memory leaks in a given code snippet
- Use Chrome DevTools to take a heap snapshot and find retained objects
- Write a component with proper cleanup of event listeners and timers
- Implement a cache with WeakRef that allows garbage collection
⚠️ Common Mistakes
Not removing event listeners when they're no longer needed — especially in SPAs that don't fully reload
Storing large data in closures unnecessarily — capture only what you need
Forgotten setInterval/setTimeout without cleanup — always store and clear IDs
Accumulating data in global arrays/objects without bounds — caches grow indefinitely
Circular references between closures can prevent GC in older engines (IE) — modern engines handle this
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Memory Management & Garbage Collection. Login to unlock this feature.