What Is Memory Leak in JavaScript: Explanation and Examples
memory leak in JavaScript happens when the program keeps using memory that it no longer needs, causing the app to slow down or crash. This usually occurs when references to unused objects are not removed, so the garbage collector cannot free that memory.How It Works
Imagine your computer's memory as a desk where you do your work. When you finish a task, you clear the desk to make space for new work. In JavaScript, the garbage collector acts like someone who cleans the desk by removing things you no longer need.
A memory leak happens when you keep putting papers on the desk but never throw away the old ones, even if you don't need them anymore. The desk gets cluttered, and you run out of space to work efficiently.
In JavaScript, this clutter happens when variables or objects are still referenced somewhere in the code, so the garbage collector thinks they are still needed and does not remove them. Over time, this wastes memory and can slow down or crash your program.
Example
This example shows a simple memory leak by keeping references to objects in an array that grows endlessly.
function createLeak() { const leakyArray = []; return function addItem(item) { leakyArray.push(item); // keeps reference to item console.log('Item added, total items:', leakyArray.length); } } const leak = createLeak(); leak({ name: 'object1' }); leak({ name: 'object2' }); leak({ name: 'object3' });
When to Use
Understanding memory leaks is important to keep your JavaScript apps fast and stable. You want to avoid leaks especially in long-running apps like web servers, games, or single-page applications where memory can slowly fill up.
Use this knowledge to check your code for places where objects are kept longer than needed, such as global variables, event listeners not removed, or caches that grow without limits.
Fixing leaks helps prevent slowdowns, crashes, and poor user experience.
Key Points
- A memory leak means memory is used but never freed.
- It happens when references to unused objects remain.
- Garbage collector cannot remove objects still referenced.
- Leads to slower performance and crashes over time.
- Watch for global variables, event listeners, and caches.