Why does the second line of code produce an error but not the third?
{ foo: 'bar' } // => 'bar'
{ "foo": 'bar' } // => SyntaxError: Invalid label
({ "foo": 'bar' }) // => { foo: 'bar' }.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The relevant part of the language specification is http://es5.github.com/#x12.4
The lookahead part means that something is only treated as an expression when it appears where a statement is expected if it does not start with
{orfunction.is a block of statements containing the expression statement
'bar'with labelfoo. Labels allow you tobreakorcontinuefrom named loops but can be attached to any statement, not just loops.The parser starts parsing this, finds an expression
"foo"and then looks for a binary operator but:is not a valid binary operator so it fails with a syntax exception.Here the parentheses enter an expression context, so the
{is treated as starting an object constructor instead of as the start of a block.