The Wayback Machine - https://web.archive.org/web/20240806212825/https://www.geeksforgeeks.org/memory-management-in-javascript/
Open In App

Memory Management in JavaScript

Last Updated : 09 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Memory management in JavaScript is handled automatically by the runtime environment, typically the JavaScript engine in web browsers or Node.js. JavaScript uses a garbage collector to manage memory and ensure that developers do not need to manually allocate or deallocate memory.

Memory Life Cycle

Irrespective of the programming language, the memory life cycle follows the following stages:

  1. Allocates the memory we need: JavaScript allocates memory to the object created.
  2. Use the allocated memory.
  3. Release the memory when not in use: Once the allocated memory is released, it is used for other purposes. It is handled by a JavaScript engine.

The second stage is the same for all the languages. However, the first and last stages are implicit in high-level languages like JavaScript.

Note: “Objects” in this context not only mean objects in JavaScript but also functions and function scopes.

JavaScript engines have two places to store data

  • Stack: It is a data structure used to store static data. Static data refers to data whose size is known by the engine during compile time. In JavaScript, static data includes primitive values like strings, numbers, boolean, null, and undefined. References that point to objects and functions are also included. A fixed amount of memory is allocated for static data. This process is known as static memory allocation.
  • Heap: It is used to store objects and functions in JavaScript. The engine doesn’t allocate a fixed amount of memory. Instead, it allocates more space as required.

Overview:

Stack

Heap

Primitive data types and references Objects and functions
Size is known at compile time  Size is known at run time
Fixed memory allocated No limit for object memory

Example: In the below example object ’employee’ is created in the heap and a reference to it is in the stack.

Javascript




const employee = {
  name: 'Rajesh',
  age: 30,
};
 
const name="Ram"
// Allocates memory for object in heap.Values
// in object are primitive,which is why they
// are stored in stack.
 
function getname(name) {
    return name;
}
// The function return value is given to stack after
// being evaluated in the heap
 
const newEmployee = employee;
// The newEmployee object will be stored in the stack and
// it will refer to the employee object in heap


Memory Management in JavaScript

Memory Management in JavaScript

Garbage Collection

Garbage collectors are used in releasing memory. Once the engine recognizes that a variable, object, or function is not needed anymore, it releases the memory it occupied. The main issue here is that it is very difficult to predict accurately whether a particular variable, object, or function is needed anymore or not. Some algorithms help to find the moment when they become obsolete with great precision.

Reference-counting garbage collection

It frees the memory allocated to the objects that have no references pointing to them. However, the problem with this algorithm is that it doesn’t understand cyclic references.

Example: In this example, the game and boy both reference each other. Thus, the algorithm won’t release the allocated memory. Setting them to null won’t make the algorithm realize that they can’t be used anymore, leading to no release of allocated memory.

Javascript




let game = {
  name: 'cricket',
};
 
let boy = {
  name: 'Ram',
}
 
game.boy = boy;
boy.game = game;
 
boy = null;
game = null;


Mark-and-sweep algorithm

This algorithm solves the above-mentioned issue. Instead of finding references to a particular object, it detects if they are reachable from the root object.

Note: In JavaScript root is the window object while in NodeJS it is the global object.

The algorithm marks objects that are not reachable as garbage and collects (sweeps) them. Thus, it is known as Mark and Sweep algorithm. In the previous example, neither the game nor the boy object can be accessed from the root object. Thus, it is marked as garbage and collected afterwards.



Similar Reads

How to solve JavaScript heap out of memory on prime number ?
JavaScript is a high-level, dynamically typed object-oriented programming language. An "out of memory" error is thrown when the program exceeds the available memory and causes overflow. It may also be caused due to an object that is too long or requires memory greater than it is allocated. Since everything in JavaScript is an object and objects are
3 min read
How does memory stacks work in Javascript ?
Introduction: The memory stack is a mechanism in JavaScript that allows us to allocate and free memory. If a programmer wants to store some data, they must first create an empty part of the heap that is called a "stack." Then, they can push and then pop values on the stack. When working with strings in JavaScript, we typically use string concatenat
3 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 situation where memory is allocated for objects that are
8 min read
How to clear cache memory using JavaScript?
Unlike mobile applications, web browsers do not provide a direct option to clear their cache memory. However, it's possible to load webpages without caching by utilizing meta tags in the HTML code. This involves instructing the browser not to remember recently loaded data, effectively bypassing the cache. Below are the approaches to clear cache mem
3 min read
Build a Memory Card Game Using HTML CSS and JavaScript
A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of both cards are matching or not. If the faces of bo
6 min read
Ferro-electric Random Access Memory
Ferro-electric Random Access Memory (FRAM) is a type of Random Access Memory, which uses a ferro-electric capacitor to achieve it's non-volatility (content is not lost when power is turned off).The di-electric constant of a ferroelectric material usually has a high value. The most widely used ferroelectric material is PZT (Lead Zirconate Titanate).
2 min read
Memory Allocation in Static Data Members in C++
C++ allows defining static data members within a class using the static keyword. When a data member is declared as static, then we must keep the following note in mind: Irrespective of the number of objects created, only a single copy of the static member is created in memory. All objects of a class share the static member. All static data members
4 min read
Memory Protection in Operating Systems
In this article, we will be discussing memory protection in operating systems. As we know that different operating systems use different forms of memory protection or separation which consists of Plan9 and Inferno, Microsoft Windows, etc. In Memory protection, we have to protect the operating system from user processes and which can be done by usin
5 min read
Tensorflow.js tf.memory() Function
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. Tensorflow.js tf.memory() function is used to get memory info of the program at the current time. This function returns a memoryInfo object with the following properties: numBytes: It
2 min read
Which one is better (unset() or $var = null) to free memory in PHP ?
In this article, we will discuss freeing the memory with unset() and using NULL value to any variable. unset(): The unset() function is an inbuilt function in PHP that is used to unset a specified variable. The unset() function just destroys or removes the variable from the symbol table. After the unset() applied on a variable, it's marked for PHP
2 min read
three90RightbarBannerImg