In JavaScript, there have traditionally been two ways of checking for equality: using the ==
operator or the ===
operator. These two operators are sufficient for most of the comparisons we perform, but there are certain edge cases that can produce some unexpected behavior. As a result, the Object.is()
method was introduced in ECMAScript 2015.
First, let’s quickly review how traditional equality comparisons are performed in JavaScript. The ==
operator loosely checks equality by first performing a type conversion and then comparing the two values. The ===
determines if two values are strictly equal to each other. When using this ===
operator, there is no implicit conversion of type, so the comparison only returns true if the operands are of the same type and have the same value.
There are some values, however, that these loose and strict equality operators don’t handle very gracefully. Let’s see the result of comparing 0
and -0
.
As we can see, both the ==
and ===
operations have determined that positive zero and negative zero are equal. In most cases this result is fine. However, because of the way the signed number system in JavaScript works, these two values are actually different. In certain scenarios, a developer may need to be able to distinguish between these two values. Unfortunately, the traditional comparison operators have no way of differentiating between the two.
In this case, we can use the new Object.is()
method to compare 0
and -0
with a different result.
In the comparison above we are passing two arguments into the Object.is()
method. These two arguments are then compared against each other and a boolean is returned, indicating whether the two values are equal. In this case, the Object.is()
method recognizes that 0
and -0
have different signs and evaluates to false
.
Another scenario in which the loose and strict equality operators differ from the Object.is()
method is when comparing NaN
values. Let’s see the result of comparing two NaN
values using traditional equality comparison.
Most developers would expect the comparisons above to return true
. However, as we can see, both the ==
and ===
operators consider NaN
and NaN
to be different. The Object.is()
method will deal with this scenario correctly by returning true
when comparing these same two values.
The Object.is()
method provides developers with a new way of comparing two values, while avoiding some of the quirky behavior produced by the ==
and ===
operators. You may not need to use this method often, but it can be invaluable in certain situations.