What Is the Difference Between ==, === and Object.is in JavaScript?
January 24, 2023
There are many ways to compare equality in JavaScript. The three most common are ===
(strict comparison), ==
(loose comparison), and Object.is
(equal comparison). What's the difference between the three? Let's take a look at this question that is often asked in interviews.
==
Loose comparison (loose equality)
When using ==
, before two values are compared, the type will be converted first.
For example, in the following three examples, the reason why true
will be printed is precisely because before the comparison, the type is converted. Otherwise, the number 1
and the string '1'
represent different values in JavaScript, and strictly speaking, they should not be equal.
Similarly, undefined
and null
are different types and different values in JavaScript, but if ==
is used, true
will be returned.
console.log(1 == "1"); // true
console.log(0 == false); // true
console.log(undefined == null); // true
==
can cause some confusion for developers because of the type conversion. Therefore, in most cases, it is not recommended to use ==
.
===
Strict comparison (strict equality)
===
does not convert the type and value, so comparing the two will return false
if they are of different types. If the value is different, false
will also be returned.
There are two exceptions though, strict comparisons will return true
when we compare +0
and -0
, and comparisons NaN
and NaN
will return false
.
+0 === -0; // true
NaN === NaN; // false
These two situations are when equality comparison Object.is
comes in handy.
Object.is
Same-value comparison (same-value equality)
Same-value comparison, as the name implies, compares whether two values are equal. Although it starts with Object, any two values can be compared. For example:
console.log(Object.is(1, 1)); // true
console.log(Object.is(1, "1")); // false
The above two problems in ===
can be fixed by using Object.is
console.log(Object.is(+0, -0)); // false
console.log(Object.is(NaN, NaN)); // true
However, if you want to check the equality of NaN
, there is a method called isNaN
in JavaScript. Whether to use it depends on the habits of the development team. If you are unfamiliar with Object.is
, you can choose to use Number.isNaN
.