{}.tostring() Uncaught Syntaxerror: Unexpected Token
Solution 1:
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
Solution 2:
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.
Solution 3:
{}
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.
Solution 4:
The parser is interpreting the {}
as a code block. You can make it parse correctly by surrounding the braces with parentheses:
({}).toString();
Post a Comment for "{}.tostring() Uncaught Syntaxerror: Unexpected Token"