What is the difference between `{}` and `()` in this code?

Destructuring_assignment # Assignment_without_declaration

He says:

{a, b} on the left side is considered a block, not a literal object.

var a, b; {a, b} = {a:1, b:2};//Syntax Error! ({a, b} = {a:1, b:2}); // it works 

what does '()' do in the second sentence?

why is '{}' in it considered an object literal?

+5
source share
4 answers

Statements should not start with curly braces in Javascript: Destructuring Traps

Alternatively, the following expression is possible:

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

It is important that the statement does not begin with a curly brace, because blocks of code begin with one.

+2
source

The first one tries to assign a value to the block, which is incorrect. Second equivalent

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

So, here you call the constructor, providing a block of properties and assigning values ​​to them.

+1
source

can I just give an explanatory explanation directly to the pattern that you linked:

I think it's pretty clear

(..) around the assignment operator, syntax is required when using the destruction assignment of an object literal without a declaration.

{a, b} = {a:1, b:2} autonomous syntax is invalid, since {a, b} on the left side is considered a block, not an object literal.

However ({a, b} = {a:1, b:2}) valid, as is var {a, b} = {a:1, b:2}

+1
source

We cannot assign any values ​​to any literals, such as an array, object, string.

for example: [a] = [1];

{a} = {1};

"a" = "b";

But we can assign a value using a comma delimiter

[a], {a} = {a: 1};

Output:

[a] - [1]

{a} - {a: 1}

Note:

Literal 1.Object should not be the first in initialization.

2. No values ​​are ever stored in a string literal.

() - qualto return statement

Whatever you specify in {} , it will automatically execute itself;

To simply install the {return;} code anywhere in the function, it will return the function.

Just take a look at the code succinct for understanding.

 var a =5;b=6; console.log(JSON.stringify({a,b})); //Output: {"a":5,"b":6} [a,b],{a,b} = {"a":1, "b":2}; console.log(JSON.stringify([a,b])); console.log(JSON.stringify({a,b})); //Output: //[1,2] //{"a":1,"b":2} var name = (function(){return "lotus"}); console.log(name); //Output: function(){return "lotus"} name = (function(){return "lotus"})(); console.log(name); //Output: lotus name = ({a, b} = {a:3, b:4}); console.log(JSON.stringify(name)); //Output: {"a":3,"b":4} 
0
source

All Articles