JavaScript Course
JavaScript
/
Advanced

Memory Leaks

Definition

A memory leak occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released (garbage collected).

Explain Like I'm New

Imagine filling up a trash can, but instead of the garbage truck emptying it every week, you just buy a new trash can. Eventually, your entire house fills with trash. In JS, if you keep adding objects to memory but never let the Garbage Collector delete them, the browser tab will eventually crash.

Real World Example

Creating a `setInterval` that updates a variable, but forgetting to call `clearInterval` when the user navigates away from the page. The interval runs forever in the background, consuming memory.

Common Use Cases

  • •App performance optimization
  • •Preventing browser tab crashes in Single Page Apps (SPAs)

Interactive Example

// CAUSING A LEAK:
let hugeArray = [];
function leakMemory() {
  // Every click adds 1MB of data that is NEVER deleted
  hugeArray.push(new Array(100000).fill('garbage')); 
}
document.getElementById('btn').addEventListener('click', leakMemory);


// PREVENTING A LEAK (In React/Modern JS):
/*
useEffect(() => {
  const handleScroll = () => console.log('scrolling');
  window.addEventListener('scroll', handleScroll);

  // CLEANUP FUNCTION: 
  // Removes the listener when component unmounts, allowing memory to be freed
  return () => window.removeEventListener('scroll', handleScroll);
}, []);
*/

Interview Questions

basic

  • How does JavaScript clear memory?

intermediate

  • What are the 3 most common causes of memory leaks in JavaScript?

advanced

  • How do you find a memory leak using Chrome DevTools?

Flash Cards

Question

What are the 3 most common causes?

Click to reveal answer
Answer

1. Accidental global variables (attaching huge data to `window`). 2. Uncleared timers and intervals (forgetting `clearInterval`). 3. Uncleared event listeners attached to DOM elements that have been removed from the screen.

Question

How do you find a memory leak?

Click to reveal answer
Answer

Open Chrome DevTools -> Memory tab -> Take Heap Snapshot. Do an action in your app (like opening and closing a modal). Take a second Snapshot. Compare the two to see which objects were not deleted and trace their 'Retainers'.