How JavaScript Variables are Stored in Memory?


In JavaScript we have two types of data types, primitive types and objects. Whenever you define a variable in JavaScript, the JavaScript engine allocates a memory to it.

Depending on whether the variable is an object or a primitive value such as string, number etc., it will be stored either in Stack or a Heap Data structure.

let name = "Samson"; // this is stored on stack
let obj = { "name" : "Roy", "age" : 35} // stored on Heap

Any data type value which is immutable is stored on a Stack data structure since it’s size is known during compilation phase.

Mutable data types such as Objects, Arrays are stored on a Heap data structure and a reference to the Object or array is stored on the stack data structure.

enter image description here