11

Here is the result from browser console (both firefox and chrome ) , false == {} works,but {} == false gives syntax error.

>> false == []
true
>> false == {}
false
>> 0 == false
true
>> false == []
true
>> false == {}
false
>> [] == false
true
>> {} == false
Uncaught SyntaxError: Unexpected token == 
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175

3 Answers3

11

In the former case, it's not clear to the parser that {} represents a value.

The following works:

var a = {};
a == false      // false

Or alternatively you can use:

({}) == false   // false

So this isn't anything specific to value comparison -- rather, it's the way the code is parsed.

Nice question!

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
3

If you run just {}, you see that it's not being parsed as an object at all - it gives undefined! Clearly, it's being parsed as a code block. Hence, {} == false is a syntax error, as there is nothing on the left side of the ==.

{}variableName is also not a syntax error for the same reason - it's an empty code block.

If you wrap it in parentheses, it is correctly parsed as an object literal, and works.

({}) == false
Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

Even this works,

 /{}/ == false;   // false 
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45