Lesson 98 – JavaScript Memory Management & Garbage Collection
Memory management is a crucial aspect of software development. In JavaScript, memory allocation and deallocation are handled automatically through a process called garbage collection. However, understanding how memory works under the hood can help you write more efficient and memory-safe applications.
What Is Memory Management?
Memory management is the process of allocating, using, and releasing memory in your program.
In JavaScript, this typically involves two major phases:
- Allocation – Reserving memory for variables, objects, and functions.
- Deallocation (Garbage Collection) – Releasing memory that is no longer in use.
Memory Life Cycle
Every time you create a variable or object, memory is allocated to store it. That memory is kept until it is no longer referenced or needed.
Phases:
- Allocate memory when declaring variables.
- Use the memory by performing operations.
- Free the memory when it's no longer needed.
Garbage Collection in JavaScript
Garbage collection (GC) is the process of automatically identifying and reclaiming memory that is no longer in use.
Key GC Concept: Reachability
The JavaScript engine determines which objects are “reachable” and keeps them in memory. If an object is no longer reachable, it is eligible for garbage collection.
let user = {
name: "Alice"
};
user = null; // The object is now unreachable and can be collected
Garbage Collection Algorithms
Most modern JavaScript engines use these two algorithms:
- Mark-and-Sweep: Marks reachable objects and sweeps (clears) the unreachable ones.
- Reference Counting: Counts the number of references to each object and collects the ones with zero references (less common due to circular reference issues).
Common Memory Leaks in JavaScript
- Global Variables – Accidentally creating globals keeps them in memory.
- Closures – Unused closures can retain memory unnecessarily.
- Detached DOM Elements – If references to removed DOM nodes persist, memory leaks can occur.
- Timers and Callbacks – setInterval or setTimeout not cleared properly.
Example Memory Leak with setInterval
function startLeaking() {
setInterval(() => {
console.log("Still here!");
}, 1000);
}
If setInterval
is not cleared with clearInterval
, the memory used by the callback function will never be freed.
Best Practices to Avoid Memory Leaks
- Avoid unnecessary global variables.
- Remove event listeners when not needed.
- Nullify references to unused objects.
- Clear intervals and timeouts when not needed.
- Be cautious with closures that retain large objects.
Summary
- JavaScript handles memory automatically, but poor code practices can lead to memory leaks.
- Understanding how garbage collection works (especially reachability) helps prevent issues.
- Keep your code clean, manage references wisely, and always release resources.
Try Your Hand
Task: Create a timer that logs a message every second and then stops after 5 seconds using setInterval
and clearInterval
.
let count = 0;
const intervalId = setInterval(() => {
console.log("Counting:", count);
count++;
if (count >= 5) {
clearInterval(intervalId);
}
}, 1000);
In This Lesson, You Learned:
- What memory management is in JavaScript.
- How the garbage collector works (mark-and-sweep, reference counting).
- Common causes of memory leaks.
- Best practices to write memory-efficient JavaScript.