Swap two numbers
C++:
int a = 3;
int b = 5;
a^=b^=a^=b;
printf("%d, %d\n", a, b); //5, 3
PHP:
$a = 3; $b = 5;
$a^=$b^=$a^=$b;
echo "$a, $b\n"; //5, 3
Javascript:
> a=3;b=5;a^=b^=a^=b;[a,b]
[ 0, 3 ]
Why? Looks like all variables initialized before all expression executed...
Your assignment in JS is equivalent to
a = a ^ (b = b ^ (a = a ^ b));
and that is evaluated from left to right and for a we get
3 ^ (5 ^ (3 ^ 5))
So an easy fix would be to write
a = (b ^= (a ^= b)) ^ a;
Welcome to the world of JS =)
In ES6, you can simply use destructing assignment:
var a = 3
var b = 5
[a, b] = [b, a]
which behaves as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With