Reputation: 29
when I try it in chrome dev tools, it shows
Uncaught SyntaxError: Unexpected token .
However if when it assign to a:
var a={}.toString();
a //[object Object]
what caused the difference?
Upvotes: 1
Views: 1056
Reputation: 48277
{}
is captured first and interpreted as a block, which has no .toString
method to call.
If you wrap the object literal in parens, like ({}).toString()
, then it works as expected.
This is because of the parsing rule priorities and the {}
tokens being overloaded to be both object and block delimiters.
Upvotes: 1
Reputation: 1074475
what caused the difference?
The state the parser is in. By default, the parser is in a state where it expects a statement. So in your example in the console, the {
looks like the opening of a block to it, not the beginning of an object initializer. (You can also give it an expression at that point, because JavaScript has the concept of the ExpressionStatement, which is a statement consisting entirely of an expression.)
But in your var a={}.toString();
code, the {}.toString()
appears on the right-hand side of an assigment, where the parser is expecting an expression, not a statement. So the {
starts an object initializer.
If you do something to make the parser expect an expression instead, it'll work in the console too:
({}).toString(); // "[object Object]"
or
+{}.toString(); // NaN, because the `+` tries to turn `[object Object]` into a number and fails
Upvotes: 3
Reputation: 101690
The parser is interpreting the {}
as a code block. You can make it parse correctly by surrounding the braces with parentheses:
({}).toString();
Upvotes: 0
Reputation: 943591
When you aren't in expression context (as is triggered by being on the right hand side of an assignment, for instance) then {}
is a block statement and not an object literal.
Upvotes: 2