+ 3

How to swap two variables in JavaScript?? i want swap() function!

var a = 10, var b 5; swap(a,b); console.log(a, b) // a = 5, b = 10

2nd Jul 2018, 5:54 PM
Hoang Anh
Hoang Anh - avatar
3 Respuestas
+ 4
es6 style [a,b]=[b,a] or with a binary operator a = a ^ b; b = a ^ b; a = a ^ b; or with a temporary variable var tmp; tmp = a; a = b; b = tmp;
2nd Jul 2018, 6:04 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 3
function swap(x,y) { a = y; b = x; // supposing that a and b are global variables }
2nd Jul 2018, 6:05 PM
777
777 - avatar
0
use temporary variable var temp; temp=a; a=b; b=temp;
10th Jul 2018, 5:15 PM
Vipul Bodhani