object destructuring without var

前端 未结 3 1728
自闭症患者
自闭症患者 2020-11-22 07:30

Why does object destructuring throw an error if there is no var keyword in front of it?

{a, b} = {a: 1, b: 2};

throws Sy

3条回答
  •  太阳男子
    2020-11-22 07:56

    If you write Javascript without semicolons, then the 'assignment without declaration' syntax should be preceded with a semicolon for it to work predictably

    let a, b
    
    ;({a, b} = objectReturningFunction()) // <-- note the preceding ;
    

    Just wanted to highlight this as it caught me out, and hopefully can save others some time figuring out why it doesn't work and/or produces weird results with code formatters like prettier.

    Indeed, it's actually right there in the accepted answer (last line of the quoted docs) but easy to miss, especially without seeing an example!

提交回复
热议问题