Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange javascript behaviour (assignments)

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...

like image 350
vp_arth Avatar asked Mar 30 '14 10:03

vp_arth


2 Answers

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 =)

like image 154
aZen Avatar answered Sep 23 '22 04:09

aZen


In ES6, you can simply use destructing assignment:

var a = 3
var b = 5
[a, b] = [b, a]

which behaves as expected.

like image 24
mikemaccana Avatar answered Sep 19 '22 04:09

mikemaccana