Memory Management in JavaScript
Last Updated :
04 Feb, 2025
Memory management is critical in JavaScript, especially for applications running in the browser or Node.js. Unlike low-level programming languages such as C or C++, JavaScript automatically allocates and deallocates memory using Garbage Collection (GC) mechanisms.
However, understanding how memory management works in JavaScript helps developers write efficient code and increase performance while avoiding memory leaks.
Understanding Memory Life Cycle
Regardless of the programming language, the memory life cycle follows three main steps:
- Allocate the memory you need – Memory is allocated when variables, objects, or functions are created.
- Use the allocated memory – The allocated memory is used during execution (reading/writing operations).
- Release the allocated memory – Once it is no longer needed, it should be released (garbage collected).
In low-level languages like C, developers manually allocate and free memory using functions like malloc() and free(). However, in JavaScript, memory management is handled automatically.
Types of Memory in JavaScript
JavaScript manages memory in two main areas:
1. Stack Memory (Primitive Data Types)
- Used for storing primitive values (e.g., number, string, boolean, null, undefined, symbol, and bigint).
- Operates on a Last In, First Out (LIFO) basis.
JavaScript
let n1 = 10;
let n2 = n1;
n2 = 20;
console.log(n1); // 10 (remains unchanged)
Here, n1 and n2 are stored in the stack, and n2 gets a copy of a’s value.
2. Heap Memory (Reference Data Types)
- Used for objects, arrays, and functions.
- Allocated dynamically and accessed via references.
JavaScript
let obj1 = { name: "Ajay" };
let obj2 = obj1;
obj2.name = "Vijay";
console.log(obj1.name); // "Vijay"
Here, obj1 and obj2 reference the same memory location in the heap.
Memory Allocation in JavaScript
1. Value Initialization
JavaScript automatically allocates memory when values are declared.
JavaScript
const n = 123; // allocates memory for a number
const s = "string"; // allocates memory for a string
const obj = { a: 1, b: null }; // allocates memory for an object and its values
const a = [1, null, "str2"]; // allocates memory for an array
2. Allocation via Function Calls
Some function calls result in object allocation:
JavaScript
const d = new Date(); // allocates a Date object
const e = document.createElement("div"); // allocates a DOM element
Some methods also allocate new objects:
JavaScript
const s1 = "string";
const s2 = s1.substr(0, 3); // s2 is a new string
JavaScript Garbage Collection (GC)
1. Mark-and-Sweep Algorithm
- The garbage collector marks objects that are still accessible (reachable).
- Unreachable objects are then swept away (deallocated).
- Memory is freed and can be reallocated for new data.
2. Reference Counting (Deprecated)
Older JavaScript engines used reference counting, which failed to handle circular references.
JavaScript
function circularRef() {
let obj1 = {};
let obj2 = {};
obj1.ref = obj2;
obj2.ref = obj1;
}
circularRef(); // Memory leak
Common Memory Issues and Optimizations
1. Memory Leaks
Memory leaks occur when memory that is no longer needed is not released. Common causes include:
var s = "This stays in memory until the page is closed";
Solution: Use let or const to limit scope.
let ele = document.getElementById("myDiv");
document.body.removeChild(ele);
The variable element still holds a reference, preventing GC. Solution: Set ele = null; after removal.
2. Using WeakMap and WeakSet
Unlike regular objects, WeakMap and WeakSet allow garbage collection of keys when they are no longer in use.
let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, "some value");
obj = null; // Now obj is eligible for GC
3. WeakRefs and FinalizationRegistry
WeakRefs and FinalizationRegistry allow developers to observe when objects are garbage collected.
const registry = new FinalizationRegistry((key) => {
console.log(`Object with key ${key} has been garbage collected.`);
});
let obj = {};
registry.register(obj, "myObject");
obj = null; // When GC runs, the callback will execute
Tools for Memory Management in JavaScript
1. Chrome DevTools
- Open DevTools (F12 or Ctrl+Shift+I).
- Navigate to Performance and Memory tabs.
- Take heap snapshots to identify memory leaks.
2. Node.js Memory Profiling
- Use process.memoryUsage() in Node.js to monitor memory.
console.log(process.memoryUsage());
- Use tools like v8-profiler and heapdump for in-depth analysis.
Similar Reads
Memory Management in JavaScript
Memory management is critical in JavaScript, especially for applications running in the browser or Node.js. Unlike low-level programming languages such as C or C++, JavaScript automatically allocates and deallocates memory using Garbage Collection (GC) mechanisms. However, understanding how memory m
4 min read
JavaScript Var Statement
The var keyword is used to declare variables in JavaScript. It has been part of the language since its inception. When a variable is declared using var, it is function-scoped or globally-scoped, depending on where it is declared. Syntax var variable = value;It declares a variable using var, assigns
7 min read
setTimeout() in JavaScript
The setTimeout() function is used to add delay or scheduling the execution of a specific function after a certain period. It's a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution. [GFGTABS] JavaScript setTimeout(function() { console.log('Hello
2 min read
JavaScript Statements
JavaScript statements are programming instructions that a computer executes. A computer program is essentially a list of these "instructions" designed to perform tasks. In a programming language, such instructions are called statements. Types of Statements1. Variable Declarations (var, let, const)In
4 min read
How to Handle Memory Leaks in JavaScript ?
JavaScript, unlike some other programming languages, uses automatic memory management. This means the developer doesn't have to explicitly free up memory when they're done with it. However, memory leaks can still happen in JavaScript if objects are not properly cleaned up. A memory leak is a situati
8 min read
Objects in Javascript
An object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime. There are two primary
4 min read
JavaScript Atomics store() Method
What is Atomics? The Atomics is an object in JavaScript which provides the ability to perform atomic operations as static methods.Just like the Math object in JavaScript all the properties and methods of Atomics are also static.Atomics are used with SharedArrayBuffer(generic fixed-length binary data
3 min read
Pass by Reference in JavaScript ?
Contrary to common belief, JavaScript is not a pass-by-reference language but Instead, it is a pass-by-value for all its variable passing. In JavaScript, when an object is passed as an argument to a function a reference to the object is passed not a direct copy of the object itself. The modification
1 min read
What is JavaScript?
JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
6 min read
Mutlithreading in JavaScript
Multithreading is the ability of any program to execute multiple threads simultaneously. As we know JavaScript is a single-threaded programming language, which means it has a single thread that handles all the execution sequentially. Single-threaded means one line of code run at once. Originally, Ja
3 min read