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 !