Introduction to the difference between two equals and three equals in javaScript

  • 2020-03-30 03:28:36
  • OfStack

In short: == convert the type first and then compare, === determine the type first, if not the same type is false.
=== = is equal to, the two sides of the comparison have to be absolutely the same


alert(0 == ""); // true
alert(0 == false); // true
alert("" == false); // true

alert(0 === ""); // false
alert(0 === false); // false
alert("" === false); // false

First say ===, this is relatively simple, specific comparison rules are as follows:

1. If the type is different, it is [unequal]
2. If both are numerical values and the same value, then [equal]; (! The exception is, if at least one of them is NaN, then [not equal]. (to determine whether a value isNaN, you can only use isNaN().)
3. If both are strings and the characters in each position are the same, then [equal]; Otherwise [unequal].
4. If both values are true or both values are false, then [equal].
5. If both values refer to the same object or function, then [equal]; Otherwise [unequal].
6. If both values are null or both are undefined, then [equal].

Again ==, the specific comparison rules are as follows:

1. If the two values are of the same type, make a === comparison. The comparison rule is the same as above
2. If two values are of different types, they may be equal. Type conversion and comparison according to the following rules:
A. If one is null and the other is undefined, then [equal].
B. If one is a string and the other is a number, convert the string to a number for comparison.
C. If any value is true, convert it to 1 for comparison; If either value is false, convert it to 0 for comparison.
D. If one is an object and the other is a value or string, convert the object to a value of the underlying type for comparison. Object to the underlying type, using its toString or valueOf methods. Js core built-in class, will try valueOf before toString; The exception is Date, which takes advantage of the toString transformation. Non-js core objects, let say (more trouble, I do not understand)
E. Any other combination (array, array, etc.) is [unequal].


Related articles: