Memory Management in JavaScript (Garbage Collection)
JavaScript automatically manages memory. This means we as programmers don't have to manually free up RAM when data is no longer needed. However, understanding how this process works will help you write more efficient and optimized code.
In this article, we'll learn how JavaScript manages memory, what "garbage collection" is, and how to avoid memory leaks.
How Memory is Managed in JavaScript
Memory management in JavaScript involves three stages:
- Memory allocation
- Usage
- Release/deallocation
// Memory allocation
let user = {
name: "Anna",
age: 28
}; // The object is stored in the heap
// Usage
console.log(user.name); // "Anna"
// When user is no longer accessible:
user = null; // Will automatically go to "garbage collection"
JavaScript uses an automatic garbage collector that tracks whether data is still accessible. If not, it gets freed.
This mainly happens based on the following principle:
- Reachability: If an object is still accessible from any active part - call stack, closures, or global scope - it won't be deleted.
- If not, it's considered unused and can be removed by the collector.
Mark-and-Sweep Algorithm
This is the most common garbage collection method. It has the following steps:
- Starts from root objects (e.g., global object)
- Tracks all objects that can be reached
- Marks unreachable objects for deletion
// Example
function createUser() {
let user = {
name: "Aram"
};
return user;
}
let u = createUser(); // user is accessible - GC won't delete
u = null; // Now GC will delete if there are no other references
Advantages of this method:
- Automatic management
- Simple semantics
Common Memory Leaks in JavaScript
Although the garbage collector is helpful, it's possible to misuse resources and cause memory leaks. Here are some common mistakes:
// 1. Global variables
function setName(name) {
globalName = name; // globalName becomes an unintended global variable
}
// 2. Forgotten timeout or interval
setInterval(() => {
console.log("Still running...");
}, 1000); // Never stops if you don't use clearInterval
// 3. Forgotten event listeners
element.addEventListener('click', () => {
console.log("Clicked");
}); // If never removed => memory leak
How to avoid:
- Use
let,constwhen creating new variables - Clean up timers and listeners when no longer needed
- Use Chrome DevTools Memory Profiler to find memory leaks
Conclusion
JavaScript provides automatic memory management, but it's our responsibility to write code that aids this process. By understanding how garbage collection works, we can avoid performance issues and memory leaks.