What is object equality in JavaScript ?
JavaScript provides us with a number of ways to check if two objects are equal. Let us demonstrate how to check whether two objects are equal.
There are three types of equality –
- Referential equality.
- Shallow equality.
- Deep equality.
Referential equality: We can say two objects are referentially equal when the pointers of the two objects are the same or when the operators are the same object instance.
We can check referential equality in 3 ways:
- === (triple equals) operator or the strict equality operator. Strictly equality refers to the equality of two values. If the two values have the same type, they are considered equal.
- == (double equals) is the loose equality operator. It converts both the values to a common type and then checks for equality.
- object.is() function.
Javascript
<script> var a = 1; var b = 1; console.log(a == b); // true var c = 10; var d = "10" ; console.log(c == d); // true const name1 = { first_name: "sarah" , }; const name2 = { first_name: "sarah" , }; console.log(name1 == name2); // false </script> |
Output:
true true false
Javascript
<script> var a = 1; var b = 1; console.log(a === b); // true var c = 10; var d = "10" ; console.log(c === d); // false const name1 = { first_name: "sarah" , }; const name2 = { first_name: "sarah" , }; console.log(name1 === name2); // false </script> |
Output:
true false false
Javascript
<script> var a = 1; var b = 1; var c = 10; var d = "10" ; console.log(Object.is(c, d)); // false console.log(Object.is(a, b)); // true console.log(Object.is(a, a)); // true const name1 = { first_name: "sarah" , }; const name2 = { first_name: "sarah" , }; console.log(Object.is(name1, name2)); // false console.log(Object.is(name1, name1)); // true </script> |
Output:
false true true false true
Shallow equality:
- A shallow equality check of objects returns the list of properties of both objects and further checks if the properties are equal.
- Shallow equality is a type of equality that occurs when the key values in both objects are equal.
Deep equality:
- Deep equality is a recursive shallow equality check.
- If the properties are objects, then the check is performed recursively on these objects.