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