0

In Javascaript, I publicly assigned the variable A. I now want to assign A to a destructured variable. But all I can think of is:

const {variable} = getVariable();
A = variable;

How can I make this into a one-liner?

  • 1
    You can't assign to an already existing variable in a destructuring assignment. Maybe just don't use destructuring? `A = getVariable().variable` – pascalpuetz Sep 25 '22 at 16:45
  • 2
    @pascalpuetz [You actually could](https://stackoverflow.com/q/27386234/1048572), but indeed `A = getVariable().variable;` is the simplest and cleanest way to write this – Bergi Sep 25 '22 at 17:22
  • @Bergi Oh wow, didn't realize that was possible. Thanks for sharing that link! – pascalpuetz Sep 25 '22 at 19:14

2 Answers2

1

You can write

({variable: A} = getVariable());

if you insist on using destructuring to assign a previously declared variable, but really there's no good reason to use destructuring here. Normal property access is so much simpler, shorter, and more readable:

A = getVariable().variable;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

You can do this

const {variable:A} = getVariable(); 
Kaneki21
  • 1,323
  • 2
  • 4
  • 22
  • From the users example `A` seems to already be defined. Thats why it needs to be solved with an assignment pattern https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#binding_and_assignment just like in @Bergis example. – Amanda Nov 17 '22 at 14:14