DEV Community

Deepanshu Gupta
Deepanshu Gupta

Posted on

Understanding the difference: Primitive Vs Reference Data types in JavaScript.

JavaScript has majorly two kind of data type categories,

  1. Primitive Data type
  2. Reference Data type

And the major differentiation between the two happens on the grounds of how the data types are stored in the memory. Below we will discuss about how this all works.

Primitive data types

These data types are stored in a much simple way than reference, below are the examples :

  • Numbers

  • Strings

  • Boolean

  • Null

  • Undefined

  • Symbols

How are they stored in the memory?

When a primitive data type is declared, it gets stored on the stack, and it is identified by the variable name used to declare it.

Let's consider an example,

let num1 = 29;
let num2 = num1;
//num1=num2=29;
//now we may reassign a new value to num1
let num1 = 45;
console.log(num1,num2);
//gives num1 = 45, but num2 = 29

Enter fullscreen mode Exit fullscreen mode

This happens because each time we declare a primitive data type, this gets stored in a stack, i.e. the computer creates room for num1 and when we assign the same value to num2, it gets a separate memory location. Therefore, any changes to num1 do not reflect upon num2, since they both are stored at different places.

Reference data types

These types of data types are particularly objects. Examples are :

  • Objects

  • Functions

  • Collections

  • Arrays

  • Dates

How are they stored in the memory?

They are stored a bit differently in the memory, let's see how.

Whenever a reference data type is created, the variable name with which it is declared gets a pointer value assigned to it instead of the actual data value, this pointer value is an address to the memory location where the reference data type value is stored, in heap, a totally different memory location than the stack.
For example,

let arr1 = [1,2,4];
let arr2 = arr1;
//now we may reassign value to arr1 = [1,2,34];
let arr1 = [1,2,34];
console.log(arr1,arr2);
//gives an output where now arr1 = arr2 = [1,2,34];

Enter fullscreen mode Exit fullscreen mode

This happens because when arr1 is created, the value gets stored in the heap, and arr1 gets a pointer as the value assigned, in the stack, and when arr2= arr1, arr2 gets a pointer with the same address value since the array was created only once, unlike in the case of primitive data type. Therefore, when a change is made to the array value, the change reflects in both arrays, since they point to the same value.

Top comments (0)