Reputation: 1205
In Chrome 63.0 and Firefox 58.0, it appears that adding an index to an object literal prevents the object from being parsed as an object.
{"a":"b"}
17:37:32.246 {a: "b"}
{"a":"b"}["a"]
17:37:36.578 VM288:1 Uncaught SyntaxError: Unexpected token :
Can anybody explain why the parser doesn't parse this the way I do? (I think there must be a bug in my implementation of the spec...) It seems to think it's not parsing an object.
Surrounding the object in brackets results in syntactically correct expression:
({"a":"b"})["a"]
17:42:03.993 "b"
Upvotes: 1
Views: 79
Reputation: 68665
{"a":"b"}["a"]
- {}
is detected as bracket body or block - not an object. Lets look an example on if
statement, you can have something like this
if(condition) {
"a": "b"
}
So actually you get an statement like "a" : "b"
which is invalid.
({"a":"b"})["a"]
- ()
evaluates the expression inside it, so {}
is detected as object
Upvotes: 4
Reputation: 6491
It has to do with the console evaluating the {}
as a block instead of an object literal.
This question is similar to "Defining a JavaScript object in console" and "Is the curly brackets object notation valid in any expression?" question on StackOverflow.
The key part from the spec is:
ExpressionStatement
: [lookahead ∉ {{
,function
}]Expression ;
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.
Upvotes: 4