Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "{} == false" incorrect javascript syntax , while "false == {}" is not ? [duplicate]

Tags:

javascript

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 == 
like image 219
DhruvPathak Avatar asked Nov 11 '14 09:11

DhruvPathak


2 Answers

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!

like image 67
Drew Noakes Avatar answered Oct 12 '22 11:10

Drew Noakes


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
like image 30
Scimonster Avatar answered Oct 12 '22 11:10

Scimonster