JavaScript Object Equality Check with Examples
Everything in JavaScript is Object
, we all know that. Oftentimes, working with objects we need to compare two objects
data whether they are the same or not. As objects
are structured data it can't be compared easily like those primitive data types. In this article, we will be seeing, how can we check object equality. So let's start without further due.
I know many of you wonder how to compare objects with JavaScript's Equality Operator
like === or ==. So why not give a try with an example? Also in ES6, there is a built-in function to check if two objects hold two same values or not. That is Object.is()
. It takes two object
and gives the result in boolean
. Let's practically see which methods give the best results.
const object_1 = {
name: 'shouts.dev'
};
const object_2 = {
name: 'shouts.dev'
};
console.log(object_1 === object_2) //false
console.log(object_1 == object_1) //true
console.log(Object.is(object_1, object_2)) //false
console.log(Object.is(object_1, object_1)) //true
Surprisingly, Equality Operator
and Object.is()
couldn't help us in this regard. Because, "==="/Object.is()
actually compare reference value in memory allocation rather than objects internal data. So that's why when comparing object_1
with object_1
it gives us true
. So when checking for an object's actual content none of the methods are providing a way.
Now question is how can we check? The answer is manually.
const object_1 = {
firstName: 'shouts',
};
const object_2 = {
firstName: 'shouts',
};
console.log(object_1.firstName === object_2.firstName) //true
console.log(Object.is(object_1.firstName, object_2.firstName)) //true
const object_1 = {
lastName: 'dev'
};
const object_2 = {
lastName: 'Dev'
};
console.log(object_1.lastName === object_2.lastName) // false
console.log(Object.is(object_1.firstName, object_2.firstName)) // false
In the above example, We compared objects
data by accessing it through .(dot) notation. For the first example, we got true
as both object data is exactly equal but for the second example we got false
as object_2's
data is different from object_1
. Hence, This is one of many ways how we can compare objects actual content.
But when we will have large object with hundreds of data where we can't afford such one by one comparison then what to do? In the next article, we will dive into deep equality check for object with nested data. So stay tuned for the upcoming article.
Above all those examples, we saw that, "===" and Object.is() basically do the same. Is there any difference between them? Yes. there is a subtle difference between them. Look at the below example carefully,
console.log(Object.is(NaN, NaN)) // true
console.log(Object.is( 0, -0)) // false
console.log(NaN === NaN) // false
console.log(-0 === 0) // true
Basically, "===" and Object.is() treat NaN and signed zero(0) differently. That's the main difference between the two of them.