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:
[a, b] = [b, a];
Β
1. Using destructuring assignment (ES6+)
In this example, we use destructuring assignment to swap values of a and b variables.
// ONLINE-RUNNER:browser;
var a = 1;
var b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
2. UsingΒ temporary variable
In this example, we use tmp temporary variable to swap a and b variables in three steps:
- assignΒ the value of
avariable to thetmp, - assign
avariableΒ with the value ofb, - assign
bvariable with the value oftmp(which have the initial value ofa).
// ONLINE-RUNNER:browser;
var a = 1;
var b = 2;
var tmp;
tmp = a;
a = b;
b = tmp;
console.log(a); // 2
console.log(b); // 1
3. UsingΒ mathematical operations
In this example, we use addition and subtraction to swap values of a and b variables.
// ONLINE-RUNNER:browser;
var a = 1;
var b = 2;
a = a + b;
b = a - b;
a = a - b;
console.log(a); // 2
console.log(b); // 1
4. Using bitwise XOR operator
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.
// ONLINE-RUNNER:browser;
var a = 1; // 0001
var b = 2; // 0010
a = a ^ b; // 0011
b = a ^ b; // 0001
a = a ^ b; // 0010
console.log(a); // 2
console.log(b); // 1
XOR operator:
βββββββ¬ββββββ¬ββββββββ
β a β b β a ^ b β
βββββββΌββββββΌββββββββ€
β 0 β 0 β 0 β
β 1 β 1 β 0 β
β 0 β 1 β 1 β
β 1 β 0 β 1 β
βββββββ΄ββββββ΄ββββββββ