Why do both "[] == true" and "![] == true" evaluate to false?
It's the way coercion works.
The first step of coercion is to convert any non primitive types to primitive types, then using a set of rules convert the left, right or both sides to the same type. You can find these rules here.
In your case [] == true
, would pass through these 4 steps:
[] == true
[] == 1
"" == 1
0 == 1
Whereas based on operator precedence the !
in ![] == true
is executed first so the expression is converted to false == true
which is obviously false
.
You can try the live demo by Felix Kling to better understand how the sameness operator works.
As per the Abstract Equality Comparison Algorithm - http://es5.github.io/#x11.9.3
Types of x and y are checked when
x == y
is to be checked.If no rule matches, a false is returned.
- For
[] == true
, rule 7 matches, so a result of[] == ToNumber(true)
is returned i.e.false
is returned. - Reason you're getting the same result for
![] == true
, because![]
returnsfalse
, andfalse == true
returnsfalse
.
To get opposite result for your second operation, add a precedence (i.e. wrap) to your expression with braces.
console.log(!([] == true)); // returns true