=== (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)
==, 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
== 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 comparisons
NaN will return
+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
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
Object.is, you can choose to use