I make 2 functions foo and bar to prevent side effect of two variables y and z.
My target is whatever happen with y, z, reassign or something else, the result final is the same.
You can see example 2 line console.log(bar(5, 7)) with same input x, y at final.
It's fine with when a reassign y, z again
y = oriZ
z = oriY
It print exactly I want ==> [8, 40]
But if I do it with shorthand reference
[y, z] = [oriY, oriZ]
It will be print ==> [undefined, undefined] at final. What happen ?
I try console.log value of it at below to see what happen
console.log(oriY, oriZ)
But it print an error at console dev tool "TypeError: Cannot set property '40' of undefined". Hmm, I got stuck to figure out what's going on?
This is a full code below
var y, z;
function foo(x) {
y++;
z = x * y;
}
function bar(curX, curY) {
var [oriY, oriZ] = [y, z]
y = curY;
foo(curX)
var [newY, newZ] = [y, z]
// I try log at line below but it go wrong in console dev tool, so I commented it out
// console.log(oriY, oriZ)
// Line code below will be make it wrong, but I don't know why.
// I guess it will chang address reference but I'm not sure.
[y, z] = [oriY, oriZ]
// I commented 2 line correct code below
// y = oriZ;
// z = oriY;
return [newY, newZ];
}
console.log(bar(5, 7))
// Why it print [undefined, undefined] here?
console.log(bar(5, 7))
//Why it print [8, 40] here?