Possible Duplicate:
Conflicting boolean values of an empty JavaScript array
What is the rationale behind the fact that
[ ([] == false), ([] ? 1 : 2) ]
returns [true, 1]?
In other words an empty list is logically true in a boolean context, but is equal to false.
I know that using === solves the issue, but what is the explanation behind this apparently totally illogical choice?
In other words is this considered a mistake in the language, something unintentional that just happened and that cannot be fixed because it’s too late or really in the design of the language someone thought it was cool to have this kind of apparent madness that I’m sure is quite confusing for many programmers?
The technical explanation of how this happens is at the same time amazing and scaring, I was however more interested in what is behind this design.
Edit
I accepted very detailed Nick Retallack explanation, even if it’s only about the technical reasons of why []==false is true: surprisingly enough it happens is because [] converted to string is an empty string and the empty string numeric value is special cased to be 0 instead of the apparently more logical NaN. With an empty object for example the comparison ({}) == false returns false because the string representation of an empty object is not the empty string.
My curiosity still remains about all this being just unanticipated (and now unfortunately solidified in a standard).
Let’s get technical. I’ll explain the logic with quotes from the ECMAScript Standard 262.
The expression
[] ? 1 : 2is very simple:So it’s true.
Now for the wild ride of what happens when you use the double equals operator. Perhaps this will help explain why you should never do this.
The behavior of == is explained in in section 11.9.3: The Abstract Equality Comparison Algorithm.
For x == y where x = [] and y = false, this happens:
Now we have [] == 0
I assume this first attempts valueOf and then rejects it because the result is the same array you started with. It then calls toString on Array, which seems to be universally implemented as a comma separated list of its values. For empty arrays like this one, that results in empty string.
Now we have ” == 0
Now we have 0 == 0
Awesome. It’s true. Pretty convoluted way of getting here though.