js reassign a value to multiple already declared variables from a function

Viewed 288

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?

2 Answers

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());

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)
}

Related