Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does accessing a property directly on an Object literal throw a SyntaxError?

Tags:

javascript

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?

like image 784
Randomblue Avatar asked Dec 18 '11 18:12

Randomblue


People also ask

What is object literal syntax?

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.

Which is the correct syntax to access an object property in JavaScript?

You can access the properties of an object in JavaScript in 3 ways: Dot property accessor: object. property. Square brackets property access: object['property']

Which is the correct syntax for creating an object literal?

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.

What are object literals used for?

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.


2 Answers

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

like image 104
Šime Vidas Avatar answered Sep 29 '22 17:09

Šime Vidas


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);
like image 43
matthijs koevoets Avatar answered Sep 29 '22 16:09

matthijs koevoets