Objects are handled differently from primitves. This is why objects cannot be compared with either strict or loose equalityโฆ itโll always be false.
const zell = { isHavingFun: true }const vincy = { isHavingFun: true }
console.log(zell === vincy) // falseconsole.log(zell == vincy) // falseHereโs why.
Objects are compared by reference
Letโs say you have an identical twin and you look exactly the same as your twin โ same hair color, same face, same clothes, same everything.
People wonโt be able to differentiate you normally because itโs hard โ you look the same after all!
Now, one easy way to differentiate between the two of you, is to ask you to show us your identity cards โ when you flash your identity cards, weโll always know who is who.
In JavaScript, each object has a identity card too. This identity card is called the reference to the object.
When you compare objects with equality operators, youโre asking JavaScript to check if the two objects have the same reference (same identity card).
This is why zell === vincy is always going to be false โ because they have different references (identity card).
Now if we tweak things a little and assign zell to vincyโฆ
const zell = { isHavingFun: true }const vincy = zellIn this case, vincyโs reference will now be zell, so zell === vincy evaluates to true.
console.log(zell === vincy) // trueChecking if two objects have the same value
If you really want to check whether two objects have the same value, you need to compare each property and value pair within the object.
To do this, you need to know how to use loops โ so weโll cover this in a later lesson.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson