Why does adding parentheses prevent an error?

后端 未结 1 1467
情书的邮戳
情书的邮戳 2021-01-04 03:55

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

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

相关标签:
1条回答
  • 2021-01-04 04:51

    { } 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 讨论(0)
提交回复
热议问题