Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, why does { a : 1 } == { a : 1 } give an error, and ({a : 1}) == {a : 1} will work?

Tags:

javascript

This is done in Firebug:

>>> {a : 1} == {a : 1}
SyntaxError: syntax error
[Break On This Error] {a : 1} == {a : 1} 

>>> ({a : 1}) == {a : 1}
false

So it needs to be ({a : 1}) == {a : 1}, why is that?

like image 784
nonopolarity Avatar asked Oct 10 '11 13:10

nonopolarity


1 Answers

Because {a : 1} is a declaration and it's not allowed to be follow by == however

({ a : 1 }) is an expression and is allowed to be followed by ==

This is basically the rules defined in the grammer.

However note that ({ a: 1} == { a: 1}) is valid. So the equivalence expression is valid.

This means that {a : 1} == { a : 1 } is simply not a valid statement.

12.4 of the ES5.1 spec says

NOTE An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

As a sidenote you will find that

({a : 1}) != {a : 1} because they are two new objects

like image 183
Raynos Avatar answered Oct 02 '22 18:10

Raynos