In my Javascript console (in Chrome) I'm trying this:
{ 'a' : 1 }
and getting SyntaxError: Unexpected token :
But this works:
['a', 1]
What gives???
In my Javascript console (in Chrome) I'm trying this:
{ 'a' : 1 }
and getting SyntaxError: Unexpected token :
But this works:
['a', 1]
What gives???
It's because curly braces have two uses - either introducing a block, or as the start of an object literal (the latter being an expression).
The console can't tell which, so it assumes a statement block, and only later finds that the contents of the block can't be parsed as statements.
For array literals with square brackets that ambiguity doesn't exist.
The ambiguity can be resolved by changing the context so that the {...}
must be interpreted as an expression rather than a statement block, e.g. by making it the RHS of an operator, wrapping it in parentheses, or passing it as a function parameter, etc.
This is a block:
{
var x = 'stuff'
function doStuff(arg) { alert(arg) }
doStuff(x)
}
It will alert stuff
.
Now, about your example: JavaScript thinks it's a block, like this:
{
'a' : 1
}
Since 'a' : 1
is not a valid statement, it fails.
Note that if you do
'x' + { 'a' : 1 }
It works, because there's no way a block could come after a +
.
You can do new Object({'a' : 1})
for that.
As others have pointed out, this is due to the fact that curly braces have dual use.
The easiest way to work around the ambiguity is by adding a pair of parentheses:
> {'a': 1}
SyntaxError: Unexpected token :
> ({'a': 1})
Object {a: 1}