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?