Swapping two variables holding integers without a temporary variable in JavaScript with Bitwise XOR operator
I recently saw this trick used to swap the values of two variables without using a temporary variable.
var a = 6;
var b = 5;
a^=b;
b^=a;
a^=b;
console.log(a); // 5
console.log(b); // 6
At first I was confused what was going on, so I wanted to take my time to describe step by step what is occurring.
^ in Javascript is the Bitwise XOR operator. A bitwise operator in JavaScript treats their operands as 32 bits of zeros and ones. From the Mozilla Developer Network, the Bitwise XOR operator “returns a one in each bit position for which the corresponding bits of either but not both operands are ones”.
To make the code more readable, the middle 3 lines could be written as:
a = a ^ b;
b = b ^ a;
a = a ^ b;
Either way, these 3 lines are written has the same meaning in JavaScript.
Now we need to convert 5 and 6 into 32 bit binary. I’m leaving off all the zeros on the left of these numbers as that would be a lot of zeros to keep displaying.
6 in binary is 110
5 in binary is 101
Since we know 5 and 6 in binary, we can substitute them into the “^” Bitwise XOR operator to see what actually is going on.
a = a ^ b; // 110 ^ 101 returns 011 which in decimal is 3 that gets set to a.
b = b ^ a; // 101 ^ 011 returns 110 which in decimal is 6 that gets set to b.
a = a ^ b; // 011 ^ 110 returns 101 which in decimal is 5 that gets set to b.