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(); }
Advertisement
Answer
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() );
From their docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_separate_from_declaration_2
Notes: The parentheses ( … ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.
However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}
Your ( … ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.