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?
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
You can access the properties of an object in JavaScript in 3 ways: Dot property accessor: object. property. Square brackets property access: object['property']
Object Literal Syntax Object literals are defined using the following syntax rules: A colon separates property name[1] from value. A comma separates each name-value pair from the next. A comma after the last name-value pair is optional.
An object literal in JavaScript allows us to create plain JavaScript objects. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With