Javascript has two ways of determining whether two values are equal.
Equality symbol
The equality symbol consists of two equals: = =
Javascript is a weakly typed language. This means that the equality symbol will cast the type in order to compare two values.
Copy Code code 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 a type conversion, so we know that using the equality symbol = = is a bad programming habit. Because of the complex type conversion mechanism in Javascript, the resulting error becomes difficult to trace.
In addition, casts of a type can have a certain effect on performance, for example, when a string is compared to a number and cast to a number.
Strict equality symbol
The strict equality symbol consists of three equals: = = =
It is similar to the operation of the equality symbol, but the strict equality symbol does not do the operation of the coercion type conversion.
Copy Code code 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 code above makes the code clearer, and returns False if the type of two values is different, which can also improve performance.
Compare objects
although = = and = = are called equality symbols, the performance will vary greatly when one of the two values of the comparison is an object.
Copy Code code as follows:
{} === {}; False
New String (' foo ') = = ' Foo '; False
New Number (10) = = 10; False
var foo = {};
Foo = = = = Foo; True
Here, no longer just compare two values for equality, it will determine whether two values refer to the same object instance, and this behavior is more like a pointer in C.
Summarize
It is strongly recommended that only strict equality symbols = = = be used. If we need to do a type conversion, we can do an explicit type conversion before comparing it to the Javascript itself, rather than the complex cast method.