xor - Why do these statements work differently in JavaScript? -


i checking out sweet little code swap 2 variables using xor function. used javascript this.

let x , y 2 variables , let x = 4, y = 6.

x = x ^ y; y = y ^ x; x = x ^ y;

it swaps variables nicely. notice i'm keeping x , y different prevent aliasing can occur due first xor.

then, observing statement, wrote: x = x ^ (y = y ^ (x = x ^ y )); swaps variable y correctly makes x 0.

also, x ^= y ^= x ^= y; seems equivalent expression yields same incorrect result in second case.

however, these statements run equivalently on java , produce same result consistently.

i used strict mode javascript.

are these 3 statements somehow not equivalent on javascript or missing critical here?

x = x ^ y; y = y ^ x; x = x ^ y; 

this works because it's like

x_1 = x_0 ^ y_0; y_1 = y_0 ^ x_1; x_2 = x_1 ^ y_1; 

then,

x_final = x_2 = x_1 ^ y_1 = x_0 ^ y_0 ^ y_0 ^ x_1 = x_0 ^ y_0 ^ y_0 ^ x_0 ^ y_0         = y_0 y_final = y_1 = y_0 ^ x_1 = y_0 ^ x_0 ^ y_0         = x_0; 

your x = x ^ (y = y ^ (x = x ^ y )); like

x_1 = x_0 ^ y_0; y_1 = y_0 ^ x_1; x_2 = x_0 ^ y_1; 

then,

x_final = x_2 = x_0 ^ y_1 = x_0 ^ y_0 ^ x_1 = x_0 ^ y_0 ^ x_0 ^ y_0         = 0 y_final = y_1 = y_0 ^ x_1 = y_0 ^ x_0 ^ y_0         = x_0; 

it have worked if used x = (y = y ^ (x = x ^ y )) ^ x;.

that's because js parses expressions left right, , want x modified value, not initial one.


Comments