Overall, JavaScript have three differenct value-comparison operations:
==
— loose equality;===
— strict equality;Object.is()
very uncommon usage.
Let’s look at the difference between these three operations:
-
===
will compare two things without type conversion. which means the first step is check the type of two things.- If
typeof(x)
is nottypeof(y)
thenreturn false
- If x, y are
Number
then compare the value of those two number. - Special case:
NaN === NaN
->return false
,+0 === -0
->return true
,null === undefined
->return false
.
- If
-
==
will do a type conversion when comparing two things;- If
typeof(x)
istypeof(y)
then compare value;- Object and Symbol: return true only when both operands reference the same object or same Symbol.
- String: return true only when both operands have the same characters in same order;
- Boolean, Number, BigInt, Symbol follow the same rule as bothe equal to another.
- Type conversion rule:
- If one is Symbol another not,
return false
; - If one is Boolean another not, convert true to 1 and false to 0;
- If one is String another is BigInt, convert String to BigInt using
Bigint()
, if conversion failedreturn false
; - If one is String another is Number, convert String to BigInt using
Number()
, if conversion failedreturn false
; - If one of the an object and other is a primitive, convert the object to a primitive;
- If one is Symbol another not,
NaN == NaN
and+0 == -0
is the same as===
, butnull == undefined
->return true
.
- If
-
Object.is()
is almost the same as strict equality===
, the diffrences areObject.is(NaN, NaN) // true
;Object.is(+0, -0) // false
;
The Usage of comparison operation
- Strict equality is almost always the correct comparison operation to use. Because it does not implement type conversion, so it is faster than loose equality;
- The built in methods including:
Array.prototype.indexOf()
,Array.prototype.lastIndexOf()
,TypedArray.prototype.indexOf()
,TypedArray.prototype.lastIndexOf()
are all using strict euqality. - When doing some legal check, undefined and null, using loose euqality is Ok.
Reference
- mdn web docs.(2023).Equality comparisons and sameness. Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
- ECMA262. (2023). https://tc39.es/ecma262/multipage/abstract-operations.html#sec-islooselyequal