How JavaScript uses Call Stack and Memory Heap?

Where does the data used by my code go?

Paulo Henrique Ferreira
2 min readJan 16, 2023
Photo by Holly Stratton on Unsplash

A JavaScript engine does two great things for us: reads our code and runs it line by line. For this to be possible, the engine allocates two pieces of memory to store the data declared in our code, and after its use, this allocated memory is free.

The first storage location used by the JS engine is the Call Stack. Here is where primitive values ​​(string, number, boolean, null, and undefined) and references to memory addresses that point to all other non-primitive structures, such as objects, arrays, and functions, are allocated in the Memory Heap. All these values ​​and references are added to the stack and executed in first-in-last-out mode. All these structures have known size before code execution.

The Memory Heap is a region of memory where all non-primitive structures are stored and can have dynamic size as a function or object and consequently result in dynamic memory allocation since the actual size is only known when the code is running.

felixgerschau.com

References

  1. (Highly recommended) https://felixgerschau.com/javascript-memory-management/
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management

--

--

Paulo Henrique Ferreira

Software Developer, Bodybuilder and passionate about knowledge.