Memory management in JavaScript
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.
Memory management in JavaScript involves three stages:
// 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:
This is the most common garbage collection method. It has the following steps:
// 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:
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:
let
, const
when creating new variablesJavaScript 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.