JavaScript Stack & Heap

[Understanding] JavaScript: Stack & Heap

Sumeet Roy
3 min readSep 22, 2019

JavaScript is a high-level Object Oriented Programming Language. Except Primitive Data Types(number, boolean, string, null and undefined) whatever you create is a reference type/object.

Primitive Data Types:

Following are the data types are known as the primitive data type.

Primitive data types are stored in the stack. Accessing data from a stack is very quick and also the memory of stack is limited. These data types always assigned by value. Consider the following code.

In the above example, we created two variables foo & koo. Value of foo is assigned to koo. As foo is a primitive data type a new memory location is created on stack & assigned with the value of foo. So when we change the value of foo, koo will not be affected.

Reference type / Object:

Consider the following example.

In the above☝️ example, we created a variable foo and assigned an object. Then we created a variable koo & assigned it with foo. We change the value of koo.name to “xyz”. In the output, foo.name is changed. Here is why 🤷‍♂…

All the reference types/objects are stored in Heap. When we assigned foo with an object, it actually created in heap and a reference or address of heap is stored inside the stack. So foo basically contains a pointer which refers to heap address.

When we assign the value of foo into koo, the foo pointer is assigned to koo. So both foo and koo is referring to same heap address. When we are changing the value in koo.name it was reflecting in foo as well.

Cloning reference type / Object:

For a modern browser which supports ES6+, you can use Spread operator.

Cloning using spread operator

Or by tradisnal approach (Works on all browser).

Cloning using JSON.parse(JSON.stringify())

In the above☝️method we are converting an object into string & again converting a string into an object. This is not recommended because of the perfomance issue.

Summary🙇:

  1. Primitive Data Types(number, boolean, string, null and undefined) are stored in STACK and they are always assigned by value.
  2. Except premitive data type whatever we create is referency type / Object.
  3. Objects are stored in HEAP and a reference of HEAP is stored in STACK. That's why objects are always assigned by reference.

--

--

Sumeet Roy
Sumeet Roy

Responses (1)