I was playing with the XOR trick for swapping values of variables, it works fine if I write it in 3 (or 2) lines, but not when I write it in 1 line, which shows some strange behavior of the ^= operator. What is going on here? Why are the 1-line and 3-line versions not equivalent?
let a = 55, b = 31;
console.log('values to swap:', a, b);
// swap with XOR trick
a ^= b;
b ^= a;
a ^= b;
console.log('swap in 3 lines', a, b);
// output: 31 55
// swap in 1 line
a = 55; b = 31;
a ^= b ^= a ^= b;
console.log('swap in 1 line', a, b);
// output: 0 55
// swap in 2 lines
// chaining only 2 ^= operations works as expected
a = 55; b = 31;
console.log('b ^= a ^= b returns ', b ^= a ^= b);
a ^= b;
console.log('swap in 2 lines', a, b);
I tested it in Chrome and Safari, got same results.
It is not possible. In JavaScript, expressions are evaluated left-to-right. You have to put this (a ^= b ^= a) && (b ^= a) equation.
That means that your condition is evaluated like this:
a ^= b ^= a ^= b;
=> a = a ^ (b = b ^ (a = a ^ b))
=> a = 55 ^ (b = 31 ^ (a = 55 ^ 31))
=> a = 55 ^ (b = 31 ^ 40)
=> a = 55 ^ 55 = 0
b = 31 ^ 40 = 55