Javascript has two ways to determine whether the two values are equal.
Equal symbol
The equality symbol consists of two equal signs: ==
Javascript is a weak-type language. This means that equal signs will cast the type in order to compare two values.
The code copy is as follows:
"" == "0" // false
0 == "" // true
0 == "0" // true
false == "false" // false
false == "0" // true
false == undefined // false
false == null // false
null == undefined // true
" /t/r/n" == 0 // true
The above code shows the result of type conversion, so we know that using the equal sign == is a bad programming habit. Due to the complex type conversion mechanism in Javascript, the resulting errors will become difficult to track.
In addition, casting of types can also have a certain impact on performance, for example, when a string is compared to a number, it will be cast to a number.
Strict equality symbol
Strict equality symbol consists of three equal signs: ===
It is similar to the operation of equal symbols, but strictly equal symbols will not perform cast operations.
The code copy is as follows:
"" === "0" // false
0 === "" // false
0 === "0" // false
false === "false" // false
false === "0" // false
false === undefined // false
false === null // false
null === undefined // false
" /t/r/n" === 0 // false
The above code makes the code clearer. If the two values have different types, they will directly return false, which will also improve performance.
Comparison object
Although == and === are called equal signs, performance will be very different when one of the two values compared is an object.
The code copy is as follows:
{} === {}; // false
new String('foo') === 'foo'; // false
new Number(10) === 10; // false
var foo = {};
foo === foo; // true
Here, it is no longer just to compare whether the two values are equal, it will determine whether the two values refer to the same object instance, which behaves more like a pointer in C.
Summarize
It is strongly recommended here to only use strict equality symbols ===. If we need to do type conversion, we can do explicit type conversion before comparison, instead of relying on Javascript's own complex casting method.