5

This works:

const { foo, bar } = someFunc();

And so does this:

let { foo, bar } = someFunc();

But if I try to destructure into already declared variables...

let foo = 0;
let bar = 0;
{ foo, bar } = someFunc();

then:

Uncaught SyntaxError: Unexpected token =

Is this by design? Is there a workaround other than declaring a temp object to receive the value? I'm doing this in a switch/case statement; foo and bar are declared on top and used after the switch. So far I can only do:

const temp = someFunc();
foo = temp.foo;
bar = temp.bar;
Marek Jedliński
  • 7,088
  • 11
  • 47
  • 57
  • [site:stackoverflow.com javascript destructuring Uncaught SyntaxError: Unexpected token](https://www.google.com/search?num=50&biw=1366&bih=678&ei=QQdZWpiQBYak0gSn_JvQAw&q=+site%3Astackoverflow.com+javascript+destructuring+Uncaught+SyntaxError%3A+Unexpected+token&oq=+site%3Astackoverflow.com+javascript+destructuring+Uncaught+SyntaxError%3A+Unexpected+token&gs_l=psy-ab.3...13011.21928.0.31632.5.5.0.0.0.0.144.489.0j4.4.0....0...1.1.64.psy-ab..1.0.0....0.UMb6wd92O1I) –  Jan 12 '18 at 19:10
  • It is indeed a duplicate of that -- but with a **much** better title and clearer text, too. So hopefully this duplicate sticks around. – T.J. Crowder Jan 12 '18 at 19:10
  • Indeed, I could not find that earlier question. But it does provide the correct answer: `({ foo, bar } = someFunc());` – Marek Jedliński Jan 13 '18 at 18:35

0 Answers0