0

I have two variables:

let a, b;

No I'd like to do a destructuring object assignment with these existing variables. When creating new variables isn't a problem, you might go ahead with:

let {x, y} = myFunc();

However, as I want to overwrite the existing variable, I'm asking myself about the preferred way. Using

{a, b} = myFunc();

will cause:

expected expression, got '='

Of course I could do:

let ret = myFunc();
a = ret.a;
b = ret.b;

But this seems to be an overhead.

How to do a destructuring object assignment to existing variables?

dude
  • 5,678
  • 11
  • 54
  • 81
  • 1
    Put the expression in parentheses `({a, b} = myFunc())`, otherwise `{}` is interpreted as a block. –  Aug 03 '16 at 12:15
  • @LUH3417 Works! Would you please be so kind and post this as an answer with background information about `()`? If so, I'll accept it. – dude Aug 03 '16 at 12:20
  • 1
    Sorry, it's a dupe, search similar questions on SO. –  Aug 03 '16 at 12:21
  • @LUH3417 Would you please be so kind and post the links where you think it is a duplicate of? – dude Aug 03 '16 at 12:23
  • Didn't find this one. – dude Aug 03 '16 at 12:26
  • @dude Easy, [first result](http://stackoverflow.com/search?q=object+destructuring) ;) – str Aug 03 '16 at 12:29
  • @str sometimes you're not able to see the wood for trees, or just using the wrong keywords. – dude Aug 03 '16 at 12:39
  • @dude Sorry, I was AFK, but str already helped out. –  Aug 03 '16 at 12:47

0 Answers0