Reputation: 26627
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.
Upvotes: 3
Views: 147
Reputation: 48761
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:
{a:1}
But this is considered a statement block with invalid syntax, since there's no statement that can begin with "a":
{"a":1}
But these don't start with a {
. They start with the b =
so the {
is considered to begin the object literal.
b = {a:1}
b = {"a":1}
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.
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:
({"a": 1})
Upvotes: 1
Reputation: 8621
Chrome evaluates console input like this:
with ((window && window.console && window.console._commandLineAPI) || {}) {
<your code here>
};
This leads to the {
}
brackets seen as extra block scope bracket and therefore getting ignored
Which then leads us to
a:1
// 1
Seen as a label
And
a={a:1}
as correct assignment
Edit:
This is also what JSLint says on this JSBin
Upvotes: 1
Reputation: 35890
My best guess would be that in the first scenario
> {a:1}
The curly braces are being ignored, and the a
is interpreted as a label.
You get the same value 1
by simply typing
> a:1
If this is correct, the second example doesn't work because double quotes aren't acceptable characters in a label.
The third and fourth examples work, because they are valid variable assignments, and the console understands the objects as objects.
Upvotes: 1