Assignment is one of the first things we are introduced to while learning JavaScript and it's of paramount importance to understand how Javascript does this to ensure that you write bug free code that doesn't changes values unintentionally.
Let's get down to business
When assignment is performed between two variables and the value that gets assigned is one of the five primitive types (Number, String, Boolean, Null and undefined) then a copy of the actual value is assigned. On the other hand, when the value getting assigned is one of the special types (Array, Function, Object), a reference to the value gets assigned.
So what does this mean for you?
Example Time!
Assignment of primitive type
const num1 = 1;
let num2 = num1;
console.log(num1, num2); // output: 1 1
num2 = 2;
console.log(num1, num2); // output: 1 2
num1
is assigned a value of type Number and then num2
is assigned num1
, since num1
is a primitive type, num2
is set as equal to the value in num1
and is an entirely separate from num1
and so reassigning num2
to 2 has no effect on num1
.
Assignment of special type
const person1 = { name: 'John Doe' };
let person2 = person1;
console.log(person1, person2);
// output: {name: "John Doe"} {name: "John Doe"}
person2.name = "Sam Smith"; // Reassigning person2
console.log(person1, person2);
// output: {name: "Sam Smith"} {name: "Sam Smith"}
The difference between both types of assignment can be seen clearly, as the reassignment of person2
affects person1
since only the reference of the value in person1
is assigned to person2
as person1
is a special type and not a primitive type.
If left unchecked this could result in unintentional bugs that'll be tricky to debug.
Top comments (0)