Why does adding parentheses prevent an error?

2020-03-01 06:19发布

Why is it when I write {}.key = 0 in the chrome console I get an error:

> {}.key = 0
> Uncaught SyntaxError: Unexpected token .

But when I encapsulate the above expression in parentheses (( )) I get no error:

> ({}.key = 0)
> 0

What exactly is going on here? I would have thought the same error I got in the first scenario still applied to the second?

Image of console output:

enter image description here

1条回答
家丑人穷心不美
2楼-- · 2020-03-01 07:06

{ } are overloaded in JavaScript syntax. They're used for both blocks (of statements) and object literals. The rule is: If a { appears at the start of a statement, it is parsed as a block; otherwise it is an object literal.

In {}.key the { appears at the start of the statement. It parses as

{
    // this is an empty block
}
.key  // syntax error here

Adding any token before { (such as () makes it parse as an object literal. For example, 42, {}.key = 0 would also work.

查看更多
登录 后发表回答