Stack And Heap

MOHAMMAD AYMONMOHAMMAD AYMON
2 min read

Table of contents

Memory Management in JavaScript

Memory management in JavaScript refers to the process of allocating and releasing memory for JavaScript objects during runtime. JavaScript has built-in mechanisms to handle memory management automatically, relieving developers from manual memory management tasks.

JavaScript engines have two places to store data:

  1. Stack: The stack is a region of memory used for managing function invocations and local variables. Each time a function is called, a new frame is added to the stack, containing information such as function arguments, local variables, and the return address. When a function completes its execution, its frame is removed from the stack. The stack operates on a Last-In-First-Out (LIFO) principle, meaning that the most recently added item is the first one to be removed. The stack is typically used for storing primitive data types and function call information.

  2. Heap: The heap is a region of memory used for dynamically allocating memory for objects. Objects, arrays, and other complex data structures are stored in the heap. Unlike the stack, memory allocation and deallocation in the heap do not follow a strict order. The heap is a large pool of memory that objects are allocated from and deallocated to as needed. JavaScript engines use various algorithms, such as garbage collection, to manage memory in the heap. The garbage collector automatically frees up memory occupied by objects that are no longer reachable, ensuring efficient memory management.

Overview:

stackheap
Size is known at compile timeObjects and functions
Primitive data types and referencesSize is known at run time
Fixed memory allocatednot limit for object memory
const employee = {
name: 'Rajesh',
age: 30,
};

const name="Ram"
function getname(name) {
    return name;
}
const newEmployee = employee;

Garbage Collection: JavaScript uses automatic garbage collection to reclaim memory occupied by objects that are no longer needed or referenced. When an object is no longer reachable from the root of the application (e.g., global variables, function scopes, or object properties), it becomes eligible for garbage collection. The JavaScript engine periodically runs a garbage collector that identifies and frees up memory occupied by these unreachable objects, making it available for future allocations.

0
Subscribe to my newsletter

Read articles from MOHAMMAD AYMON directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MOHAMMAD AYMON
MOHAMMAD AYMON