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:

 

1. Using destructuring assignment (ES6+)

Edit

In this example, we use destructuring assignment to swap values of a and b variables.

2. Using temporary variable

Edit

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

3. Using mathematical operations

Edit

In this example, we use addition and subtraction to swap values of a and b variables.

4. Using bitwise XOR operator

Edit

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.

XOR operator:

See also

Edit
  1. JavaScript - bitwise XOR operator

  2. JavaScript - array destructuring with rest parameter

References

Edit
  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
1
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