EN
JavaScript - XOR swap algorithm
7 points
In this short article, we would like to show how to make number variables swap using the XOR swap algorithm using JavaScript.
Hint: the motivation to use XOR swap is when we work on the divices that have limited operating memory - e.g. micro controllers.
Quick solution:
xxxxxxxxxx
1
let x = 3, y = 6;
2
3
x = x ^ y;
4
y = y ^ x;
5
x = x ^ y;
6
7
console.log(`x=${x}, y=${y}`);
How does it work?
The XOR operation can be inverted - it means, we do not lose any information with that operation. By executing it 3 times we are able to change variable value places.