Howard Howard - 12 days ago 7
Javascript Question

javascript unexpected token . with `{}.toString()`

My question is why following is incorrect

function hello () {
{}.toString();//Unexpected token .
}


But correct with
return
:

function hello () {
return {}.toString();
}


No idea how parser works for the incorrect version, is
{}
treated as
BlockStatement
? If yes, then why?

Thanks for detail explaination

Answer

No idea how parser works for the incorrect version, is {} treated as BlockStatement?

Exactly.

...why?

Purely because that's the way the grammar is designed. { would be ambiguous between starting a block and starting an object initializer when the parser is expecting a statement (which it is there), so the grammar says it starts a block. Thus, { starts a block, } ends it, and the . doesn't make sense because the parser is expecting a statement (or a closing } for the function body).

But in the second example. because the { is after return, the parser is expecting an expression (not a statement), so { starts an object initializer.

Anything to put the parser in a state where it's expecting an expression will make it treat that { as the beginning of an object initializer. Parentheses are commonly used in that case:

function hello() {
    ({}).toString();
}

Of course, that function doesn't do anything, because you're not using the result of toString...