Sample one (these evaluate to true):
{} + [] == 0
{} + 1 == 1
Please understand the difference between your expressions and the following:
({} + []) == 0
({} + 1) == 1
Considering that the parenthesised expressions evaluate to "[object Object]"
(and "[object Object]1"
respectively), it will become clear why the division yields NaN
.
Sample two is a different thing.
Are there special equality conditions relating to 0 in javascript?
Yes. 0
is the only falsy number, which makes a difference when comparing with booleans (where false
will be cast to 0
).
1 == "1" == 1/1
Check the evaluation of this:
(1 == "1") == 1/1 // casting the string to a number
(1 == 1) == 1
true == 1 // casting the boolean to a number
1 == 1
true
Since 1/1
is 1
and equality is commutative, the same holds for 1 == ("1" == 1/1)
But this will evaluate false even though choosing any two will evaluate true.
0 == "0" == 0/1
No "but":
(0 == "0") == 0/1 // again, casting the string to a number
(0 == 0) == 0
true == 0 // again, casting the boolean to a number
1 == 0
false
Again it doesn't matter whether we do (0=="0)==0
or 0==("0"==0)
Even without the typecasting, in plain boolean logic is clear that
(true == true) == true
will have a different result than
(false == false) == false
JavaScript does not support chained comparison operators, the operations will be implicitly nested. If you need to test three values for equality, do (false == false) && (false == false)
.