Home > Article > Web Front-end > Explanation of usage of equality(==) in JavaScript
This article brings you an explanation of the usage of equality(==) in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Where is the magic
The projects I have been responsible for recently involve front-end, so I tried to write js. When processing the non-null value of a field, tagert_value == '' was used to judge, and then a very strange thing happened. Some users reported that when their target_value = 0, the non-null value verification failed. . When debugging the problem, I tried the following in the console status bar:
> 0 == '' < true
I seem to know where the problem lies. . . I don't understand the judgment logic of == clearly, so I plan to find the official documentation and take a look.
Equality (==, !=)
1. If the types of the two expressions are different, attempt to convert them to string, number, or Boolean.
2、NaN is not equal to anything including itself.
3、Negative zero equals positive zero.
4、null equals both null and undefined .
5、Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.
6、Every other comparison is considered unequal.
Looked at the official explanation of equality and saw the first one You will know why the result is true. If the types of both sides of the expression are inconsistent, the comparison method will first try to convert them to string, number, or Boolean, and then perform the comparison (equal conditions: the same string, mathematically equal numbers, the same object, the same Boolean value ).
Seeing this, it is basically clear. When comparing 0 == '', the type was converted first. Then let's take a look at who is converted?
> Number('') < 0 > var b= '' > b.toString() <'0'
It is very obvious that when int == string, the string is first converted into the corresponding int value and then compared.
The following is a strong introduction to === (strict equality). Strictly speaking, it looks very powerful. Its official name is Identity (===. !==). Identity has a bit of a suspense-solving feel to it.
Look at the official introduction:
Identity (===. !==)
These operators behave identically to the
equality operators except no type conversion is done, and the types must
be the same to be considered equal.
In daily development, if it is not possible to ensure that the types of variables in the comparison expression are consistent twice, it is recommended to use Identify (===) to compare whether they are equal. If the variable types are consistent, you can directly use Equality (==) to compare.
The above is the detailed content of Explanation of usage of equality(==) in JavaScript. For more information, please follow other related articles on the PHP Chinese website!