最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does adding parentheses prevent an error? - Stack Overflow

programmeradmin2浏览0评论

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:

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:

Share Improve this question edited Jun 23, 2019 at 7:08 Shnick asked Jun 22, 2019 at 14:19 ShnickShnick 1,3911 gold badge18 silver badges39 bronze badges 1
  • One is a statement and one is an expression. As an expression {} returns an object. As a statement it is a code block – slebetman Commented Jun 22, 2019 at 14:27
Add a ment  | 

1 Answer 1

Reset to default 15

{ } 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.

发布评论

评论列表(0)

  1. 暂无评论