In this post, we are going to discuss what is primitive and reference types in Javascript. First of all, let see what is a primitive type?
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods.
So let me explain this above line. Primitive types in Javascript are string
, int
,boolean
,undefined
,null
, and symbol
which is available in ES6.
These are the types that are immutable(not changeable) in nature. let's see an example.
let firstname = "aditya";
console.log(name); // aditya
let lastname = name;
console.log(lastname); // aditya
name = "kumar"
console.log(lastname); // aditya
Here on the second last line, we have reassigned the name="kumar"
but when we console.log(lastname);
. It is still showing aditya
why?
Well to answer this question is Primitive does not actually reassign the value to the same variable it creates a copy of it instead of changing the value of an existing variable.
Whereas when we look into the reference type it will behave differently. let see an example first with an object.
var sportsCar = {
name: "mastang",
color:"grey"
}
// Here we will changes its value
sportsCar.name = "Ferrari"
console.log(sportsCar);
If you run the above code and console.log(sportsCar)
you will get an updated value something like this.
{
name: "Ferrari",
color:"grey"
}
Reference type are functions
, objects
and Array
. These are the types that are passed by reference which means, unlike primitive type where we copy the value in reference type we pass the pointer of the same value.
Primitive values are stored in the stack as the value of primitive type is fixed whereas reference types are stored in Heap. The size of the reference type value is dynamic.
These are the major difference between primitive type and reference type. I hope this post help you understand primitive and reference type.
Thank you for reading.