What is the behavior of typing {a:1} giving 1, and {a:1, b:2} giving an error in a Javascript console?

The second line is giving you a SyntaxError because the { token at the beginning of it causes an ambiguity, the parser treats it as if it were a Block statement, not the start of an object literal.

For example, a valid Block statement:

{ foo: 'bar' }

The above looks like an object literal, but it isn’t, because the code is evaluated in statement context.

It will be parsed as a Block, that contains a labelled statement (foo), followed by an expression statement ('bar').

To ensure that you are using the grammar of an object literal, you can wrap it with parentheses (also known as the grouping operator):

({ foo: 'bar' })

The grouping operator can only take Expressions, therefore there is no ambiguity.

See also:

  • Why the open quote and bracket for eval(‘(‘ + jsonString+ ‘)’) when parsing json string

Leave a Comment