Member-only story
Mystery behind JS Object Equality ( === )
Lets us understand the mystery
Equality operators (==
or ===
) both work differently for objects (Type of array
is an object
in JS ) when compared to other primitive types.
const a = "Erode";
const b = "Erode";
console.log(a == b) //true
console.log(a === b) //true
console.log("Erode" === "Erode") //true
console.log("Erode" == "Erode") //true
As expected every comparisions ends up with true
const a = {city:"Erode"};
const b = {city:"Erode"};
console.log(a == b) //false
console.log(a === b) //false
console.log(a == a) //true
console.log(a === a) //true
console.log(b == b) //true
console.log(b === b) //true
As you can see same properties and same values is not equal objects
As mentioned earlier, we are actually comparing the references not values, incase of object
typeof {city:”Erode”}
— object
typeof 1
— number
So be careful when you are comparing object and (array) in javascript.
So how to compare the values of the objects
If order of the elements should be matched, we can compare by converting to string
JSON.stringify(a) === JSON.stringify(b)
If elements can be of any order in both the arrays, we can do the following
Object.entries(a).sort().toString()===Object.entries(b).sort().toString()
Convert to an array, sort and then convert to string, compare it, or if u r using packages like lodash
, u can use _isEqual