3

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.

1
  • FYI, there's no such thing as a JSON object statement. In a JavaScript program, b={"a":1} is object literal notation resulting in a JavaScript object structure... not JSON data. The notation used looks similar, but the resulting data is different. Commented Dec 10, 2012 at 15:21

3 Answers 3

1

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}

12.4 Expression Statement

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})
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

it is indeed seen as a label
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.