2

Suppose I have a function that returns multiple values as following:

const myFunc = (x, y) => {
  return {xSquared: x*x,
          ySquared: y*y}
}

In my main app program, I have two global variables (i.e. they are declared with var right at the beginning and meant to be shared across the entire app).

var xSquared = 0
var ySquared = 0

Now, in a another function, I want to invoke myFunc as following:

const calcSquare = () => {
  let num1 = 3
  let num2 = 4
  const {xSquared, ySquared} = myFunc(num1, num2)
}

The destructuring above does not alter the values of the global variables xSquared and ySquared. If I want to achieve that, I have to explicitly assign the destructured outcome to them as following:

const calcSquare = () => {
  let num1 = 3
  let num2 = 4
  const {x2, y2} = myFunc(num1, num2)
  xSquared = x2
  ySquared = y2
}

My question: is the scope of destructured outcome always local? Is there a way to avoid the additional step like above if I want to assign the destructured outcome to global variables directly? Happy New Year !

Tristan Tran
  • 1,351
  • 1
  • 10
  • 36
  • 1
    I _think_ you have a typo in your question. I _believe_ you meant "_destructuring above does **NOT** alter the values_" - if that was your intent, this cannot be done because destructuring creates these variable within the scope of the closure that is created by the function call. You can prove this by removing the function wrapper and it will work after you remove `const` and surround the entire expression with `()` like this: `({x2, y2} = myFunc(num1, num2))`. Additionally, may I recommend you become more vigilant with the use (or lack of) semi-colons. – Randy Casburn Jan 01 '21 at 02:03
  • @RandyCasburn Thanks. Someone marked my question as duplicate with a link to another thread. Basically it is like what you explained. – Tristan Tran Jan 01 '21 at 02:32

0 Answers0