I’m playing with JSON objects in the Chrome console and I came across this unusual behaviour:
> {a:1}
1
> {"a":1}
SyntaxError: Unexpected token :
> b={a:1}
Object
> b={"a":1}
Object
Why does the first statement return 1 instead of an object, and why does the second statement work? I expected the first two statements to return the same output as the last two statements.
A JavaScript expression statement can not start with a
{because it would cause an ambiguity for the interpreter, which could also see it as a statement block.So this is considered a statement block with a statement label and a numeric literal instead of an object literal:
But this is considered a statement block with invalid syntax, since there’s no statement that can begin with
"a":But these don’t start with a
{. They start with theb =so the{is considered to begin the object literal.This means that all you need to do is start the expression statement with a different character to make it valid.
For example, you could wrap it in parentheses, and it will work: