7

When trying to access the property a of the object {}

{}.a

I get the error

SyntaxError: Unexpected token .

With parens all is fine:

({}).a

Why do I get an error in the fist place? Is there ambiguity?

RightSaidFred
  • 11,209
  • 35
  • 35
Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • JavaScript syntax just doesn't allow that. – Eliasdx Dec 18 '11 at 18:30
  • The expression `{}` evaluates to a new native object which has no own properties. Are you trying to access one of the `Object.prototype` methods? – Šime Vidas Dec 18 '11 at 18:42
  • 1
    possible duplicate of [Immediately accessing an object's property](http://stackoverflow.com/questions/7518538/immediately-accessing-an-objects-property) – RightSaidFred Dec 18 '11 at 18:46

2 Answers2

15

The curly braces are interpreted as a block statement, not as an object literal. You cannot begin an expression statement with a left curly brace.

The specification states:

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.

Source: http://es5.github.com/x12.html#x12.4

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
1

the {} are there to build the object. usually you first assign the new object to a variable.

var o = {
    a: "b"
};

console.log(o.a);

but this is also possible:

console.log({
    a: "b"
}.a);