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

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.

Similar Reads

Memory Life Cycle

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

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....

Garbage Collection

...

Mark-and-sweep algorithm

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....

Contact Us