First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.
#3. Value Types vs Reference Types
Value Types (PRIMITIVES)
When primitive types (string, number, boolean, undefined, null) are assigned to variable , variable stores value itself.
Let’s check example below
let x = 10;
let y = x;x = 20;console.log(x, y);
What will be logged on the console?? Think about for a moment and scroll.
Did you success guessing the result??
As i told you at the top, x
and y
stores value itself since number is primitive type. That is why variable y
stores 10 and keep storing it.
The data stored in memory would be like this:
As a result, changing value of x
to 20 has nothing to do with value of y
.
value of y
can only be changed when we assign new value to variable y
itself.
Reference Types (OBJECTS)
What kind of type would store reference, not the value? It is object type.
Object type is basically everything except primitive type. Most used object type is array, object and function. Let’s see another example below
const me = {
name: ‘dongho’,
age: 20,
isMale: true,
};const copy = me;me.age = 30;console.log(me, copy);
What will be logged on the console??
Think about for a moment and scroll.
In this case, unlike primitive type, value of copy
has changed even though we didn’t change its value. Why did this happen??
When me
is assigned to copy
, both of them store reference that is same since they are object type. And the reference is basically pointing to the value of object.
Assigning 30 to me.age, result in change of object value. And since me
and copy
are sharing same reference that is pointing to object value , now copy.age
is also 30.
Now you can easily understand why these are happening.
const a = 1;
a = 2;
When 1 is assigned to constant variable a
, 2 can’t be reassigned to a
since a
stores value itself.
const me = {
name: ‘dongho’,
age: 20,
isMale: true,
};me.age = 30;console.log(me);
However when you change object key’s value, it is possible. Because object me
stores the reference and we didn’t change reference. We just changed value that reference is pointing.
Conclusion
Sometimes i got an unexpected result since i was assigning value to variable without knowing this simple concept. Hope this help you guys like me who didn’t know about the difference between value and reference type.
This story is written with simplified explanation for better understanding. If you want to learn more detail check out here.