object destructuring without var

2019-01-01 01:03发布

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

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

throws SyntaxError: expected expression, got '='

The following three examples work without problems

var {a, b} = {a: 1, b: 2};
var [c, d] = [1, 2];
    [e, f] = [1, 2];

Bonus question: Why do we not need a var for array destructuring?

I ran into the problem doing something like

function () {
  var {a, b} = objectReturningFunction();

  // Now a and b are local variables in the function, right?
  // So why can't I assign values to them?

  {a, b} = objectReturningFunction();
}

2条回答
旧人旧事旧时光
2楼-- · 2019-01-01 01:35

The issue stems from the {...} operators having multiple meanings in JavaScript.

When { appears at the start of a Statement, it'll always represent a block, which can't be assigned to. If it appears later in the Statement as an Expression, then it'll represent an Object.

The var helps make this distinction, since it can't be followed by a Statement, as will grouping parenthesis:

( {a, b} = objectReturningFunction() );
查看更多
回忆,回不去的记忆
3楼-- · 2019-01-01 01:44

Reference from MDN :

Redeclaring the same variable within the same function or block scope raises a SyntaxError.

if (x) {
  let foo;
  let foo; // SyntaxError thrown.
}

Temporal dead zone and errors with let

查看更多
登录 后发表回答