Primitive VS Non-Primitive/Reference Type In JavaScript
Let’s understand the difference and working of primitive vs non-primitive in 5/min.
Primitive data types are: String, Number, Boolean, Undefined, Null
Non-Primitive/Reference type are: Array , Object, Function
Now let’s first understand how these values get stored in memory?
Primitive values are stored in Stack by value while non-primitive gets stored as a reference.
So when you define a variable let name=” Humza ”; this gets stored into the stack, let’s understand it with an example.
let name=” Hamza”;
let newName=name;
name=” Sajid ”;
console.log(newName);
Now guess the output will be “Hamza” or “Sajid”?
It will be “Hamza” as we know primitive values get stored into a stack as a value so when one value gets changed it will not affect the other one.
So what happens in Heap Case?
Heap is a large but slow data structure that stores non-primitive values.
So when we define an object
let obj1={name: “Humza”, age: 21}
let obj2=obj1;
obj1.name=” Ashir ”;
console.log(obj2);
Now again make an output guess?
Well now the output value is [Ashir]as obj2 get updated with obj1 because we know the object is a non-primitive data type and stack only contain the address while values are stored into the heap, and when we assigned
obj2 = obj1 the obj2 stores the address, not values.
I hope this article helps you in understanding JavaScript fundamental concepts, if you like this hit the follow button.