Equal operator
Strict equal operator
Comparison objects
Conclusion
JavaScript has two ways to determine whether two values are equal.
Equal operator
The equal operator consists of two equal signs: ==
JavaScript is a weakly typed language, which means that the equal operator will be used for comparison Two values are cast.
"" == "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 table shows forced type conversion, which is the main reason why using == is widely considered to be a bad programming habit. Due to its complex conversion rules, it can lead to problems that are difficult to track down.
In addition, forced type conversion will also cause performance consumption. For example, in order to compare a string with a number, it must be forced to a number in advance.
Strict equal operator
The strict equal operator consists of three equal signs: ===
Unlike ordinary equals Operator, the strict equal operator does not perform type conversion.
"" === "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 results are clearer and beneficial to code analysis. If the two operand types are different, they are definitely not equal and will help improve performance.
Comparison objects
Although the == and === operators are both equal operators, when one of the operands is an object, the behavior It's different.
{} === {}; // false new String('foo') === 'foo'; // false new Number(10) === 10; // false var foo = {}; foo === foo; // true
The equal operator here compares not whether the values are equal, but whether they belong to the same identity; that is, only the same instance of the object is considered equal. This is a bit like is in Python and pointer comparison in C.
Note: In order to see the difference between == and === more intuitively, please refer to JavaScript Equality Table
Conclusion
It is strongly recommended to use the strict equal operator. If a type needs to be converted, it should be done explicitly before comparison, rather than using the complex coercion rules of the language itself.
The above is the JavaScript advanced series - equality and comparison in types. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!