haltersweb
haltersweb

Reputation: 3139

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 ="

Upvotes: 1

Views: 311

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

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}

Upvotes: 3

Related Questions