Skip to main content

Command Palette

Search for a command to run...

JavaScript Stack and Heap memory

Published
•2 min read•View as Markdown
JavaScript Stack and Heap memory

Before we talk about memory allocation in java script let us first understand what is memory allocation.

Memory allocation is a process of reserving memory space for purpose such as storing data or program instructions.

With respect to programming ,memory allocation is storing data/data types in a memory space.

In programming languages such as Java script memory allocation is done automatically by the inbuilt Java engine via garbage collection.

Now, memory is split into stack memory and heap memory.

Stack memory is a place where primitive data types such as like numbers, booleans , and references.

In JavaScript, the stack is primarily used for keeping track of function call execution contexts.

  • Each time a function is called, a new execution context is created and pushed onto the call stack.

  • This execution context includes information such as local variables, function arguments, and the return address.

  • When a function completes execution, its execution context is popped off the stack.

Heap memory is a place where non-primitive datatypes like objects and arrays.

  • Objects in JavaScript are allocated memory on the heap, and variables hold references (pointers) to those objects.

  • When an object is created using the new keyword or object literal syntax, memory is allocated for that object on the heap.

  • JavaScript engines use various garbage collection algorithms to reclaim memory occupied by objects that are no longer reachable or in use.

  • Unlike languages like C or C++, JavaScript developers don't directly manage memory allocation and deallocation on the heap; instead, it's handled automatically by the engine.

In simple terms when data is stored in stack we get a copy of it where as if we store data in heap we get a reference of the data [ Any updates or changes occur the original value also gets changed ].

In summary, in JavaScript, the stack is primarily used for managing function call execution contexts, including local variables and function arguments, while the heap is used for storing objects created during the execution of a program. The JavaScript engine handles memory allocation and deallocation automatically, primarily through garbage collection mechanisms.