Difference between == and ===

"===" is called strict operator, "==" is called equality operator.

The rules of operation for strict operators are as follows:

(1) Values ​​of different types
If the types of the two values ​​are different, return false directly.

(2) Primitive type values ​​of the same class

When comparing values ​​of the same primitive type (numeric, string, boolean), true is returned if the values ​​are the same, and false if the values ​​are different.

(3) Composite type values ​​of the same class

When comparing data of two composite types (objects, arrays, functions), it is not whether their values ​​are equal, but whether they point to the same object.

(4)undefined和null

undefined and null are strictly equal to themselves.

null === null //true    undefined === undefined //true

The equality operator compares data of the same type exactly like the strict equality operator.

When comparing data of different types, the equality operator first converts the data and then compares it with the strict equality operator. Type conversion rules are as follows:

(1) Values ​​of primitive types

Primitive types of data will be converted to numeric types and then compared, strings and boolean values ​​will be converted to numeric values.

(2) Object and primitive type value comparison

When an object (here refers to a generalized object, including values ​​and functions) is compared with the value of the original type, the object is converted into the value of the original type, and then compared.

(3)undefined和null

Both undefined and null are false when compared to other types of values, and true when compared to each other.

(4) Disadvantages of equality operators

The type conversion hidden by the equality operator has some counterintuitive results.

' ' == '0'  //false
0 == ' '  //true
0 == '0'  //true

false == 'false'  //false
false == '0'  //true

false == undefined  //false
false == null  //false
null == undefined  //true

So it is recommended to try not to use the wait operator.

As for whether using the equality operator will have unintended effects on subsequent code, the answer is yes.

 

Reprinted from https://www.zhihu.com/question/31442029

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325368898&siteId=291194637