Boolean Evaluation Of Javascript Arrays
Solution 1:
It has to do with the The Abstract Equality Comparison Algorithm versus the algorithm used to tranform a value to a boolean.
By looking at the spec, we can see that the point number 9. is the only one that defines what should be happening when Type(left side value) is Object. However it's specifying that the right side value has to be either String or Number.
9 . If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
Looking at [] == true
:
typeof []
is 'object'
so we are fine, but typeof true
is not 'string'
or 'number'
, it is 'boolean'
, so it fallback to the last statement, point number 10.
10 . Return false.
However !![]
translates into !!Boolean([])
, and since []
is a thruty value (objects are), it's the same as writing !!true
, which returns true
.
Post a Comment for "Boolean Evaluation Of Javascript Arrays"