It seems to me that the operators ==
and ===
work equally. For example:
1 == 1 // True
1 === 1 // True
1 == 2 // False
1 === 2 // False
The ==
operator in short and is often found in other programming languages. So why ===
in general?
Answer 1, Authority 100%
===
and ! ==
are operators strict comparisons. It means that the operands have different types, they are not equal. For example:
1 === "1" // Returns False
1! == "1" // Returns True
null === undefined // Returns False
Operators ==
and ! =
are operators, say, rude comparisons. That is, if the operands have different types, JavaScript tries to somehow convert them to become comparable. For example:
1 == "1" // Returns True
1! = "1" // Returns False
null == undefined // Returns True
It is interesting to notice that in contrast to ===
, the operator ==
is not transitive :
"0" == 0 // True
0 == "" // True
"0" == "" // False
It is not very easy to remember the rules of this coarse comparison, and sometimes it happens that it works as an unexpected way. Therefore, I recommend using ===
instead of ==
.
Even I do not remember the small parts of the operator ==
, so let’s see in Specifications, Paragraph 11.9.3 :
Abstract Equality Comparison Algorithm
Comparison x == y, where x and y are values, returns True or False. This comparison is made as follows:
- if Type (x) is the same as Type (Y), then
- If Type (X) – undefined, return True.
- if Type (x) is NULL, return True.
- if Type (x) – Number, then
- If X is Nan, return False.
- If Y is Nan, return False.
- if X has the same numeric value as Y, return True.
- if x is +0 and y equal to -0, return TRUE.
- if x is -0 and y equal to +0, return TRUE.
- Return False.
- If type (x) is String, then return True if X and Y have an absolutely identical sequence of characters (the same length and with the same symbols in the appropriate positions). Otherwise, return False.
- if Type (x) is Boolean, return True if X and Y are both are or true, or false. Otherwise, return False.
- Return True if X and Y are referring to the same object. Otherwise, return False.
- If x is Null and Y – undefined, return True.
- if X is undefined and y – null, return True.
- If Type (X) – Number and Type (Y) – String,
Return the result of the comparison X == TONUMBER (Y).- if Type (X) is String and Type (Y) – Number,
Return the result of the comparison Tonumber (x) == y.- If Type (x) is Boolean, return the result of the Tonumber (x) == y comparison result.
- If Type (Y) is Boolean, return the result of the comparison X == Tonumber (Y).
- If Type (X) is either string, or Number, and Type (Y) – Object,
Return the result of the comparison X == Toprimitive (Y).- if Type (X) – Object and Type (Y) – String, or Number,
Return the result of the comparison ToprimiTive (x) == y.- Return False.