The Object.is() method checks if two values are the same.
Example
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
trueor 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
NaNand both have the same value
Example 1: Javascript Object.is()
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
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
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 treatsNumber.NaNas not equal toNaNwhileObject.is()does the opposite.
Recommended Reading: