-1

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?
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
  • 1
    `var [newY, newZ] = [y, z][y, z] = [oriY, oriZ];` - what is this statement suppose to do? What are you expecting here? – Yousaf Sep 04 '21 at 07:35
  • 1
    Try adding semicolons at the end of your statements… – deceze Sep 04 '21 at 07:36
  • @deceze Is there a good dup for ASI fails like this? – Barmar Sep 04 '21 at 07:41
  • @Yousaf When foo(curX) run, it will change value y, z from `var y, z` at global scope again. So I make a original state of y, z by line `var [oriY, oriZ] = [y, z]`. When foo(curX) finish. I got a new state of y and z so I set `var [newY, newZ] = [y, z]`. Because I got new state, I change y and z to original state. Finally I return new state of y and z. – Phan Trong Hieu Sep 04 '21 at 07:41
  • @PhanTrongHieu You're getting screwed by ASI not adding a semicolon where you expect it to. So `[y, z] = [oriY, oriZ]` is being appended to `var [newY, newZ] = [y, z]` and it's executing `var [newY, newZ] = [y, z][y, z] = [oriY, oriZ]` – Barmar Sep 04 '21 at 07:45
  • 1
    That's why it's generally not a good idea to depend on ASI. – Barmar Sep 04 '21 at 07:45

1 Answers1

0

You need to put a semicolon at the end of line 12.

If you don't put a semicolon where I said, Ide perceives what you wrote in the next line as a continuation of the code on that line. And your code looks like this:

image: i.ibb.co/9sdSFtg/carbon.png

ercüment
  • 138
  • 2
  • 6