Table of contents
Hello everyone, tired of searching and being confused about why two similar objects return false when we compare them. So, today I am here to solve all your doubts and make sure you got the concept of it.
Objects in JS?
You must be curious that what are Objects In Javascript. Is it for storing values as we do in arrays? or it's like storing a single variable? or is none of these as we mentioned? and why study a new concept?
Okay!! I have got it that you guys have lots of confusion regarding the objects and that's a valid one. So, have a chill pill.
So, guys do you know that Objects is also one of the data types in js. Including the below mentioned:
But, Objects are the Non-Primitive data types and the rest are Primitive. So again a question comes what is Primitive and Non-Primitive Data Types?
Primitive Data types: These are the data types that are immutable
and once created can't change their value, but can be reassigned to a new one. These data types are also called in-built data types because they are predefined from the first. eg:- Number, string, boolean
Non-Primitive Data types: These are the data types that are, mutable
that is we can change the value after the creation. eg:- Object
Let's come back to the topic, so objects are one of the data types in js which helps us store the data. The object can be created by the curly braces {...}
and with some properties in it. The property is a key: value
pair, where the key is to be a string and the value can be anything like a number, string, boolean ..etc
Why false?
When we compare two objects in javascript it returns false because JavaScript deals with similar object properties as a different one. That is in In JavaScript, two objects are considered equal only if they are the same object, not just if they have the same properties and values, and in JavaScript objects are assigned and compared by the reference, not by the value
When we compare the obj1
& obj2
we are comparing their reference not their value of it. As we see above that they have the same values but it returns false
in output. and as we have read above that they are just different objects with the same properties and values.
So, can't we get true? when we have the same properties and value? Yes, you can!!
How true?
In order to get true, the objects must be the same.
What do you mean by it, buddy?
Let's see with the help of an example
In the above code, we can see that we have created the object obj
and assigned the values of obj
to refObj
.
i.e refObj
and obj
are the same object, so the comparison returns true
. This also means that refObj
is a reference to the obj
object and the comparison are actually of the same object.
Summary
To compare different objects with the same properties and values it returns false. So for comparison, we need to assign a reference variable to that object.