JavaScript grammar: indexing object literals is syntactically forbidden?

In Chrome 63.0 and Firefox 58.0, it seems that adding an index to the object literal does not allow the object to be parsed.

{"a":"b"} 17:37:32.246 {a: "b"} {"a":"b"}["a"] 17:37:36.578 VM288:1 Uncaught SyntaxError: Unexpected token : 

Can someone explain why the parser doesn't parse this the way I do? (I think there should be a mistake in my specification implementation ...) It seems that this is not a parsing of the object.

An environment in parentheses results in a syntactically correct expression:

 ({"a":"b"})["a"] 17:42:03.993 "b" 
+2
javascript syntax grammar
source share
2 answers

This is because the console evaluates {} as a block instead of an object literal .

This question is similar to "Defining a JavaScript object in the console" and "Is the curly brace of an object notation valid in any expression?" on stackoverflow.

The key part from the specification :

ExpressionStatement : [lookahead ∉ { { , function }] Expression ;

NOTE. ExpressionStatement cannot begin with opening curly because it can make it ambiguous with Block . In addition, ExpressionStatement cannot begin with the keyword function , because that can make it ambiguous with FunctionDeclaration.

+4
source share

{"a":"b"}["a"] - {} is defined as a body or block of braces - not an object. Let's see an example in an if , you can have something like this

 if(condition) { "a": "b" } 

So you get a message like "a" : "b" , which is not valid.

({"a":"b"})["a"] - () evaluates the expression inside it, so {} is defined as an object

+4
source share

All Articles