Languages
[Edit]
EN

JavaScript - swap two variables

0 points
Created by:
Nathanial-Donald
584

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:

  1. assignΒ the value of a variable to the tmp,
  2. assign a variableΒ with the value of b,
  3. assign b variable with the value of tmp (which have the initial value of a).
// 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   β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

See also

  1. JavaScript - bitwise XOR operator

  2. JavaScript - array destructuring with rest parameter

References

  1. Bitwise XOR (^) - JavaScript | MDN
  2. Destructuring assignment - JavaScript | MDN

Alternative titles

  1. JavaScript - swap values of two variables
  2. JavaScript - swap places of two variables
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
πŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

β€οΈπŸ’» πŸ™‚

Join