2

I read the following code here:

({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20

What is the difference between that and the following:

{ a, b } = { a: 10, b: 20 };
console.log(a); // 10
console.log(b); // 20

Considering that they have the same outcome.

P.S. The point is the parentheses around the assignment expression

Pegtomous
  • 79
  • 6

1 Answers1

2

Your second example shouldn't work. You should see an error.

let a, b;
{ a, b } = { a: 10, b: 20 };

// Uncaught SyntaxError: Unexpected token '='

The reason is that the curly brackets { a, b } are considered a block not an object literal.

// This is a block
{
    console.log('Hello world');
}

When surounded by parentheses it's considered an object literal

({ hello: world })

Note: 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 const {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.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_without_declaration

Molda
  • 5,619
  • 2
  • 23
  • 39