As the title states, why does:
> !!1=="1"
equal
True
and
> !!2=="2"
equal:
False
Likewise, why does > "1"==true
equal true
and > "2"==true
equal false
I'm baffled. Are these just bugs in JS or what's going on here?
javascript
As the title states, why does:
> !!1=="1"
equal
True
and
> !!2=="2"
equal:
False
Likewise, why does > "1"==true
equal true
and > "2"==true
equal false
I'm baffled. Are these just bugs in JS or what's going on here?
Best Answer
As per the Operator precedence rules, logical
!
has higher priority over==
. So, in both the cases,!!
is evaluated first.Note: Truthiness of various objects have been explained in this answer of mine.
First Case
!1
will be evaluated tofalse
, since1
is considered Truthy. Negating again we gettrue
. So the expression becomesNow, the coercion rules kick in as you have used
==
operator, which evaluates as per the The Abstract Equality Comparison Algorithm defined in ECMAScript 5.1 Specification,So,
true
will be converted to a number, which is 1 as perToNumber
algorithm for Boolean values. Now the expression becomesNow,
So,
"1"
will be converted to a number and that will give 1, as per theToNumber
algorithm. That is why it showstrue
in the first case.Second Case
The same rules are applied here.
becomes
then
which becomes
which is not
true
, that is why the second case printsfalse
.