EN
JavaScript - swap two variables
0 points
In this article, we would like to show you how to swap two variables in JavaScript.
Quick solution:
xxxxxxxxxx
1
[a, b] = [b, a];
In this example, we use destructuring assignment to swap values of a
and b
variables.
xxxxxxxxxx
1
var a = 1;
2
var b = 2;
3
β
4
[a, b] = [b, a];
5
β
6
console.log(a); // 2
7
console.log(b); // 1
In this example, we use tmp temporary variable to swap a and b variables in three steps:
- assign the value of
a
variable to thetmp
, - assign
a
variable with the value ofb
, - assign
b
variable with the value oftmp
(which have the initial value ofa
).
xxxxxxxxxx
1
var a = 1;
2
var b = 2;
3
var tmp;
4
β
5
tmp = a;
6
a = b;
7
b = tmp;
8
β
9
console.log(a); // 2
10
console.log(b); // 1
In this example, we use addition and subtraction to swap values of a
and b
variables.
xxxxxxxxxx
1
var a = 1;
2
var b = 2;
3
β
4
a = a + b;
5
b = a - b;
6
a = a - b;
7
β
8
console.log(a); // 2
9
console.log(b); // 1
In this example, we use the XOR operator to swap values of a
and b
variables.
Note: With this solution, you can swap only integers.
xxxxxxxxxx
1
var a = 1; // 0001
2
var b = 2; // 0010
3
β
4
a = a ^ b; // 0011
5
b = a ^ b; // 0001
6
a = a ^ b; // 0010
7
β
8
console.log(a); // 2
9
console.log(b); // 1
XOR operator:
xxxxxxxxxx
1
βββββββ¬ββββββ¬ββββββββ
2
β a β b β a ^ b β
3
βββββββΌββββββΌββββββββ€
4
β 0 β 0 β 0 β
5
β 1 β 1 β 0 β
6
β 0 β 1 β 1 β
7
β 1 β 0 β 1 β
8
βββββββ΄ββββββ΄ββββββββ