There are multiple ways of swapping two variables without using third variable in programming. Using Bitwise XOR(^) is one of them. Suppose you have two variables a and b which values are respectively 50 and 100. And if you perform Bitwise XOR operation three times and assign the value respectively to a, b and a - you will find the swapped values which are a = 100 & b = 50.
Things will be more clear if you notice the truth table of Bitwise XOR(^):
X | Y | X ^ Y |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Let's do the operations in binary since machine understand only machine code/binary.
a = 50 (base 10) -> 0110010 (base 2)
b = 100 (base 10) -> 1100100 (base 2)
a = a ^ b
0110010
1100100
-------------
(XOR)1010110
b = a ^ b
1010110
1100100
-------------
(XOR)0110010 [Equivalent to 50(base 10)]
a = a ^ b
1010110
0110010
-------------
(XOR)1100100 [Equivalent to 100(base 10)]
Finally a = 100 and b = 50
To know more about Bitwise XOR, you can visit the official documentation of MDN
Top comments (8)
Another approach:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // Output: 2
console.log(b); // Output: 1
I wonder which is speedier in JavaScript?
In general bitwise operators tend to be faster. But in terms of clean and maintainable code, the tuple approach is preferred and the difference is negligible.
Does other languages like java, python, dart e.t.c support tuple approach?
In java you cannot use this approach. You have to use bitwise approach or others. In case of python, I'll be surprised if you cannot use something like this.
Other languages that I am sure you can use this approach are Swift and Rust.
For dart I really do not know.
This is what I would do too. It's far more readable and easier to see what intention is without having to understand Bitwise XOR
Bitwise operations are fun to play with. While they are generally frowned upon because they make code harder to follow, there is a special place in my heart for XOR. There is no logical equivalent to Bitwise XOR in JavaScript, so you end up writing code like this:
Once every few years, I come across this and add an eslint ignore to use XOR...and a clarifying comment, because I don't expect everyone to know it at a glance.
Yeah that's awesome 🔥
Don't think like that before, new thing is learned. Thanks