> 0 == ""
True
> 0 == " "
True
> 0 == " "
True
> 0 == "0"
True
When we use == operator to do a comparison operation. There are a few cases we should be careful of, for example when we use “==” to compare 0 with “” or “ “ because all of the cases return true.
The reason is the operand on the right hand of operator == is automatically transformed to the same type as the left hand operand. In this case, the left hand operand’s type is Number so the right hand operand is transformed to the type Number as well [1].
We can see this when we try to explicitly transform these strings to type Number.
> Number("0")
0
> Number("1")
1
> Number("")
0
> Number(" ")
0
> Number("a")
NaN
> 0 == Number("0")
true
> 0 == Number(" ")
True
It looks pretty strange when Number(“”) or Number(“ “) return 0 and Number(“a”) return NaN.
As stated in mozilla.org[2] that “In most cases, using loose equality is discouraged. The result of a comparison using strict equality is easier to predict, and may evaluate more quickly due to the lack of type coercion.”. The summary of how type conversion works in Javascript when using == operator is shown in this table [3].
Ref:
[1]
https://262.ecma-international.org/5.1/#sec-11.9.3
[2]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Top comments (0)