The Object.is()
method checks if two values are the same.
Example
let obj1 = { a: 1 };
// comparing the object with itself
console.log(Object.is(obj1, obj1));
// Output: true
is() syntax
The syntax of the is()
method is:
Object.is(value1, value2)
Here, is()
is a static method. Hence, we need to access the method using the class name, Object
.
is() Parameters
The is()
method takes in:
- value1 - the first value to compare.
- value2 - the second value to compare.
is() Return Value
The is()
method returns a Boolean
value:
true
- if the two arguments have the same valuefalse
- if the two arguments don't have the same value
Conditions for Same Values
Two values are the same if one of the following holds:
- both
undefined
- both
null
- both
true
or bothfalse
- both strings of the same length with the same characters in the same order
- both the same object (means both objects have the same reference)
- both numbers and
- both +0
- both -0
- both
NaN
- or both non-zero and both not
NaN
and both have the same value
Example 1: Javascript Object.is()
// objects with same values
console.log(Object.is("JavaScript", "JavaScript"));
// Output: true
// objects with different values
console.log(Object.is("JavaScript", "javascript"));
// Output: false
// compare null values
console.log(Object.is(null, null));
// Output: true
In the above example, we checked whether the two parameters that are passed to the is()
method are same or not.
Example 2: is() With Custom Objects
// create an object
let obj1 = { a: 1 };
// create another object
// with identical properties as obj1
let obj2 = { a: 1 };
// returns true because both arguments
// have the same reference
console.log(Object.is(obj1, obj1));
// Output: true
// returns false because obj1 and
// obj2 have different references
console.log(Object.is(obj1, obj2));
// Output: false
In the above example, we used the is()
method to check whether obj1 and obj2 have the same values.
In spite of sharing identical properties and values, we get false
as an output because obj1 and obj2 have different references.
By contrast, comparing obj1 with itself gives us true
because the reference is the same.
Example 3: is() With Special Cases
// Special Cases
console.log(Object.is([], [])); // false
console.log(Object.is(0, -0)); // false
console.log(Object.is(-0, -0)); // true
console.log(Object.is(NaN, 0 / 0)); // true
The above examples help to test some quirky behaviors of JavaScript. They don't have to be memorized and are in fact grasped as we get familiar with the language.
Notes:
- The
==
operator applies various coercions to both sides (if not the same Type) before testing for equality whileObject.is()
does not. - The
===
operator treats the number values -0 & +0 as equal and treats Number.NaN as not equal toNaN
whileObject.is()
does the opposite.
Also Read: