Javascript: The Call Stack and Heap

Ryan Leibering
3 min readMar 11, 2022

The Memory Heap, or just “the Heap”, is a core concept in understanding how Javascript stores and access data. Join me on a visual journey into the Heap, where we will explore how this mechanism interacts with the Stack to store and provide access to complex data types.

The Call Stack

As explained in a previous blog, the Stack is a mechanism which keeps track of a machine’s place in a script. Data is queued in a First-In, Last-Out order through a declaration phase and an evaluation phase.

So, why does the Heap exist?

The Heap

The Heap functions as a separate memory storage mechanism for storing complex data items, which are collections of multiple primitive data values. Unlike with primitive items, where values are stored and accessed by their variable names, complex data can’t be represented by a single variable in the stack because they contains multiple primitive values.

Using the code snippet below, lets explore how complex objects interact with the Stack:

The machine reads the code line-by-line and is declared on the Stack as normal, operating in a First-In-Last-Out order. The Heap isn’t actually accessed until the evaluation phase of the declared object variable, where the machine attempts to evaluate the complex data.

When the machine evaluates result, it is instructed to create a storage location on the Heap and to fill it with the contents of the variable. The heap then returns an address known as a “Pointer” to the Stack and stores it inside the variable.

The difference between how primitive variables and complex variables also alters the behavior of future evaluations. Because the complex data variable is actually storing a pointer, not a primitive data item, any future evaluations that call the complex data variable receive the pointer and not the actual data.

Unlike with primitive data variables, any manipulation that calls the new complex data variable will still manipulate the same complex data that the first variable is pointing to. This is known as a “shallow” copy, because it only copies the pointer, not the data. A deep copy would create a new object on the Heap and create a new address to pass back to the variable.

Resources:

A special thanks to Academind for their video on data types.

--

--