Why does !{}[true] evaluate to true in JavaScript?
{}[true]
is [true]
and ![true]
should be false
.
So why does !{}[true]
evaluate to true
?
Solution 1:
I believe that's because plain {}[true]
is parsed as an empty statement block (not an object literal) followed by an array containing true
, which is true
.
On the other hand, applying the !
operator makes the parser interpret {}
as an object literal, so the following {}[true]
becomes a member access that returns undefined
, and !{}[true]
is indeed true
(as !undefined
is true
).
Solution 2:
Because {}[true]
does not return true
, but undefined
, and undefined
is evaluated as false
:
http://jsfiddle.net/67GEu/
'use strict';
var b = {}[true];
alert(b); // undefined
b = !{}[true];
alert(b); // true