2

I need to reassign the value of two differents variables. My code is like this:

const func = () => {
    do something;
    return {a, b}
}

Then I declare the two variables outside a if/else block with let :

let a = b = '';

And in the if/else i need to assign to the two variables the value returned form the function:

if(condition) {
   a, b = func();
}

How can i reassign the value returned from the function to the variables?

matteo
  • 115
  • 1
  • 7
  • 1
    Does this answer your question? [Return multiple values in JavaScript?](https://stackoverflow.com/questions/2917175/return-multiple-values-in-javascript) And: https://stackoverflow.com/questions/29044427/javascript-how-do-i-return-two-values-from-a-function-and-call-those-two-variab – ikiK May 01 '21 at 19:31
  • It works when declaring the variables but the problem is that I need to declare them outside the if/else block and inside I need to reassign the values of the function. For some reasons it gives me an error – matteo May 01 '21 at 19:40

2 Answers2

2

You simply need to add parentheses around the assignment to have it parse as an expression rather than a block. MDN gives this example:

let a, b;
({a, b} = {a: 1, b: 2});

So in your case you would need

// For example
let a, b;
const func = () => ({a: 1, b: 2});
({a, b} = func());
iz_
  • 15,923
  • 3
  • 25
  • 40
0

You are mentioning errors, we don't see that, please make https://stackoverflow.com/help/minimal-reproducible-example for next time.

This is how it can be done:

const func = () => {
  return ["a", "b"]
}

let a, b

if (true) {
  const res = func()
  a = res[0]
  b = res[1]
  console.log(a)
  console.log(b)
}
ikiK
  • 6,328
  • 4
  • 20
  • 40