The operators ===
and !==
are the comparison operators strict . This means that if the operands have different types, they are not the same. For example,
1 === "1" // false
1 !== "1" // true
null === undefined // false
The operators ==
and !=
are the comparison operators relaxed . That is, if the operands have different types, JavaScript tries to convert them to be comparable. For example,
1 == "1" // true
1 != "1" // false
null == undefined // true
It is worth mentioning that the operator ==
is not transitive , unlike ===
.
"0" == 0 // true
0 == "" // true
"0" == ""// false
It is not very easy to remember all the rules of relaxed comparison, and sometimes it works in a counterintuitive way. Therefore, I recommend using ===
instead of ==
.
I do not remember all the little details of the operator ==
, so let's take a look at the specification, point 11.9.3:
The abstract equality comparison algorithm
The comparison x == and , where x e and are values, return true or false . This comparison is made as follows:
If Type (x) and Type (y) are the same,
If Type (x) is Undefined , return true .
If Type (x) is Null , return true .
If Type (x) is Number ,
If x is NaN , return false .
If and is NaN , return false .
If x is the same value of Number as and , return true .
If x is +0 e and is -0 , returns true .
If x is -0 e and is +0 , returns true .
Returns false .
If Type (x) is String , return true if x e and are exactly the same sequence of characters (with the same length and the same characters in the corresponding positions). Otherwise, return false .
If Type (x) is Boolean , return true , if x e and both are true or both are false . Otherwise, return false .
Returns true if x e and refer to the same object. Otherwise, return false .
If x is null e and is undefined , return true .
If x is undefined e and is null , return true .
If Type (x) is Number and Type (y) is String ,
returns the result of the comparison x == ToNumber (y) .
If Type (x) is String and Type (y) is Number ,
returns the result of the comparison ToNumber (x) == and .
If Type (x) is Boolean , return the result of the comparison ToNumber (x) == and .
If Type (y) is Boolean , return the result of the comparison x == ToNumber (y) .
If Type (x) is String or Number , and Type (y) is Object ,
returns the result of the comparison x == ToPrimitive (y) .
If Type (x) is Object and Type (y) is String or Number ,
returns the result of the comparison ToPrimitive (x) == and .
Returns false .
This answer is a translation of my answer to the same question on the Russian site .