Why is this JavaScript not interpreted as a code block when semi-colon is used?
Asked Answered
M

1

6

In Chrome version ^72 if I run the following JavaScript there are no errors.

{ prop: p } = { prop: 'prop' }
>> { prop: 'prop' }

So the line of code is interpreted as an expression statement, unexpectedly.

But if I run the same code with a semi-colon at the end it runs as expected.

{ prop: p } = { prop: 'prop' };
>> Uncaught SyntaxError: Unexpected token =

This is expected since the initial { tells the JavaScript engine that it is a code block unless we disambiguate with parentheses.

Why does this occur with the semi-colon but not without it?

Maritamaritain answered 10/12, 2018 at 19:25 Comment(0)
T
5

Why does this occur with the semi-colon but not without it?

Chrome uses a very simple test to see whether a line is an object literal or not: Does the line start with a { and end with a }? If yes, the line is evaluated as an expression.

{ prop: p } = { prop: 'prop' } passes that test, but { prop: p } = { prop: 'prop' }; does not.


See Odd behaviour of comparison of object literals for more info (different input, same reason).

Thermion answered 10/12, 2018 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.