Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Memory management is the process of allocating, using, and freeing memory in your application. JavaScript handles this automatically through garbage collection, but understanding how it works helps you write more efficient code and avoid memory leaks.
JavaScript automatically allocates memory when you create objects
Unused memory is automatically freed by the garbage collector
No need to manually allocate or free memory like in C/C++
Memory is automatically allocated when you create variables, objects, arrays, or functions.
const number = 42; // Allocates memory for number
const string = "hello"; // Allocates memory for string
const obj = { name: "John" }; // Allocates memory for object
const arr = [1, 2, 3]; // Allocates memory for arrayYour code reads and writes to the allocated memory during execution.
obj.age = 30; // Write to memory
console.log(obj.name); // Read from memory
arr.push(4); // Modify memoryWhen memory is no longer needed (unreachable), the garbage collector automatically frees it.
function createUser() {
let user = { name: "Alice" }; // Memory allocated
return user.name;
} // user object becomes unreachable -> garbage collectedModern JavaScript engines use the Mark-and-Sweep algorithm. It works by identifying which objects are still "reachable" from the root (global object, currently executing functions), and removing everything else.
The garbage collector starts from the root and marks all reachable objects.
Unmarked objects are removed from memory (garbage collected).
Global variables are never garbage collected because they're always reachable.
// BAD: Accidental global
function createUser() {
user = { name: "John" }; // No 'let' or 'const' - creates global!
}
// GOOD: Use proper scope
function createUser() {
const user = { name: "John" }; // Local variable
return user;
}Timers keep references to their callbacks, preventing garbage collection.
// BAD: Timer never cleared
const data = fetchLargeData();
setInterval(() => {
console.log(data); // data stays in memory forever
}, 1000);
// GOOD: Clear timer when done
const data = fetchLargeData();
const timer = setInterval(() => {
console.log(data);
}, 1000);
// Later:
clearInterval(timer); // Allows data to be garbage collectedEvent listeners keep references to the DOM element and callback.
// BAD: Listener not removed
const button = document.getElementById('btn');
const bigData = new Array(1000000);
button.addEventListener('click', () => {
console.log(bigData.length); // bigData stays in memory
});
// Button removed from DOM but listener and bigData still in memory
// GOOD: Remove listener
const button = document.getElementById('btn');
const bigData = new Array(1000000);
function handleClick() {
console.log(bigData.length);
}
button.addEventListener('click', handleClick);
// When done:
button.removeEventListener('click', handleClick);Closures keep references to their outer scope variables.
// BAD: Entire object stays in memory
function createHandler() {
const bigData = fetchLargeData(); // 10MB of data
return function() {
console.log(bigData.id); // Only need ID but entire object stays
};
}
// GOOD: Extract only what you need
function createHandler() {
const bigData = fetchLargeData();
const id = bigData.id; // Extract just the ID
return function() {
console.log(id); // bigData can be garbage collected
};
}Storing references to removed DOM elements prevents garbage collection.
// BAD: Keeping reference to removed element
const elements = [];
function addElement() {
const div = document.createElement('div');
elements.push(div); // Store reference
document.body.appendChild(div);
}
function removeElement() {
const div = elements.pop();
div.remove(); // Removed from DOM but still in array!
}
// GOOD: Clear references when removing
const elements = [];
function removeElement() {
const div = elements.pop();
div.remove();
// Reference is gone, can be garbage collected
}// Manual memory monitoring
console.log('Memory:', performance.memory);
// {
// usedJSHeapSize: 10000000, // Current memory usage
// totalJSHeapSize: 15000000, // Total allocated
// jsHeapSizeLimit: 2172649472 // Maximum available
// }
// Performance API
if (performance.memory) {
const used = performance.memory.usedJSHeapSize / 1048576;
console.log('Memory used:', used.toFixed(2), 'MB');
}Avoid accidental globals. Block-scoped variables are easier to garbage collect.
Always remove event listeners when components unmount or elements are removed.
Use clearTimeout() and clearInterval() to prevent memory leaks.
For caching or metadata storage, weak references allow garbage collection.
Set large objects to null when done to help garbage collector.
Extract only needed data before creating closures.
JavaScript automatically manages memory via garbage collection
Objects are freed when they become unreachable
Remove listeners, clear timers, nullify references
Use DevTools to detect and fix memory leaks