0

Problem

Is it possible to overwrite multiple variables assigned with let

const somefunction = (data) => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data})

let {a, b, c, d} = somefunction(3)

Now, how can one overwrite {a, b, c, d} in one statement after calling someFunction with a different argument?

Possible Solutions

Not working! (obviously)

const somefunction = (data) => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data})

let {a, b, c, d} = somefunction(3)
{a, b, c, d} = somefunction(5)

Working

This seems to work, but my prettier will remove the leading semicolon (+ the syntax is crazy)

const somefunction = (data) => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data})

let {a, b, c, d} = somefunction(3)
;({a, b, c, d} = somefunction(5))

are there other ways?

Fabian Bosler
  • 2,310
  • 2
  • 29
  • 49
  • You need to wrap {} in () in an arrow function that has no brackets for grouping statements: `const somefunction = data => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data})` – mplungjan Jun 19 '20 at 11:35
  • Adding the semicolon and wrapping `()` is the [only way](https://stackoverflow.com/questions/27386234/). You need to change prettier settings. – adiga Jun 19 '20 at 11:35
  • add manually an semicolon `let {a, b, c, d} = somefunction(3);` – bill.gates Jun 19 '20 at 11:36

2 Answers2

7

You need to wrap {} in () in an arrow function that has no brackets for grouping statements:

const somefunction = data => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data});

const {a,b,c,d} = somefunction(3)
console.log(a,b,c,d)

Or use {} and return

const somefunction = data => {
  return {a:1+data, b:2-data, c: 2*data, d: 3+1*data}
};

const {a,b,c,d} = somefunction(3)
console.log(a,b,c,d)

Overwrite using let:

const somefunction = data => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data});

let {a,b,c,d} = somefunction(3);
console.log(a,b,c,d);

({a,b,c,d} = somefunction(5));

console.log(a,b,c,d);

Overwrite using var ( I wouldn't ;) )

const somefunction = data => ({a:1+data, b:2-data, c: 2*data, d: 3+1*data});

var {a,b,c,d} = somefunction(3);
console.log(a,b,c,d);

var {a,b,c,d} = somefunction(5);

console.log(a,b,c,d);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

It's ugly, but you can use var instead of let.

const somefunction = (data) => {return {a:1+data, b:2-data, c: 2*data, d: 3+1*data}}

var {a, b, c, d} = somefunction(3)

console.log(a,b,c,d)

var {a, b, c, d} = somefunction(4)

console.log(a,b,c,d)
Moritz Roessler
  • 8,542
  • 26
  • 51
  • That is most certainly a solution. I was under the impression not to use var anymore. What are the drawbacks? – Fabian Bosler Jun 19 '20 at 11:43
  • 2
    @FabianBosler The only drawback is that your declaration will be [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) and it won't be block scoped. – Moritz Roessler Jun 19 '20 at 11:44