简体   繁体   中英

Destructuring giving parsing error

I'm trying to understand destructuring in ES2015 (ECMAScript 6).

I want a function to work on some variables and reassign the new variables back.

In the example below I have created a function to initialize foo and bar, and another function to change foo and bar.

I have then created three functions that use foo and bar. Two of them work, and one does not. I can't seem to figure out why.

Please share any insight to assist my understanding.

Thanks!

 function initializeFooBar() { let foo = 1, bar = 2; return {foo, bar}; } function changeFooBar(f, b) { let foo = f*2, bar = b*2; return {foo, bar}; } function fooBarWorks() { let {foo, bar} = initializeFooBar(); console.log(foo + bar); // 3 } function fooBarAlsoWorks() { let f = 1, b = 2, {foo, bar} = changeFooBar(f, b); console.log(foo + bar); // 6 } function fooBarDoesntWork() { let {foo, bar} = initializeFooBar(); {foo, bar} = changeFooBar(foo, bar); // causes parsing error console.log(foo + bar); } fooBarWorks(); // writes 3 to console fooBarAlsoWorks(); // writes 6 to console fooBarDoesntWork(); // doesn't run due to "parsing error unexpected tolken =" 

You need to change:

{foo, bar} = changeFooBar(foo, bar);

to:

({foo, bar} = changeFooBar(foo, bar));

because { in this case is interpreted as a opening of a block of code.

Surrounding the assignment with () disambiguates the meaning of { .

According to MDN documentation :

The ( .. ) around the assignment statement is required syntax 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM