This article describes in detail the equality symbols and strict equality symbols in javascript. You can refer to the following two methods in Javascript to determine whether the two values are equal.
Equal sign
An equal sign consists of two equal signs: =
Javascript is a weak type language. This means that the equal sign will force the conversion type to compare two values.
The Code 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 equal sign = is a bad programming habit. The complex type conversion mechanism in Javascript makes it difficult to trace the errors.
In addition, forced conversions of types also affect the performance. For example, when a string is compared with a number, it is forcibly converted to a number.
Strictly equal sign
Strictly equal signs consist of three equal signs: =
It is similar to the operation of equal symbols, but strictly equal Symbols do not perform the forced type conversion operation.
The Code 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 code above makes the code clearer. If the two values have different types, false is returned directly, which improves the performance.
Comparison object
Although = and = are called equal symbols, when one of the two values of the comparison is an object type, the performance is very different.
The Code 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 two values are equal. It will judge whether two values reference the same object instance. This behavior is similar to a pointer in C.
Summary
We strongly recommend that you only use the strictly equal sign =. If we need to perform type conversion, we can perform explicit type conversion before comparison, instead of relying on the complicated forced conversion method of Javascript itself.