How to Swap Variables
In this article we will present 3 ways to swap values in two variables, using JavaScript. The first two can be applied in any programming language, the third is JavaScript specific.
The task:
We have two variables a, b holding a value each. We want to assign the value of b in variable a and the value of a in variable b.
1. Using a temporary variable
A first natural try is to do something like this:
let a = 3
let b = 5
a = b
b = a
// a === 5, b === 5
That doesn't work because we loose the initial value of variable a, after assign to it, the value of variable b. So we need to create a variable to store the initial value of a. So:
let a = 3
let b = 5
let temp // our temporary variable
temp = a
a = b
b = temp
// a === 5, b === 3
2. Without using a temporary variable
This solution works only for numerical values.
let a = 3
let b = 5
// let ai be the initial value of a and bi be the initial value of b
a = a + b // a === ai + bi
b = a - b // b === a - bi === ai + bi - bi === ai
a = a - b // a === ai + bi - ai === bi
// a === 5, b === 3
3. Using array destructuring
Before we go to the solution lets review the array destructuring. Array destructuring syntax allows as to quickly define varibles and store in them elements of an array. For example:
let arr = [1,2]
let [x,y] = [arr]
// x === 1, y === 2
The second line in the above example defines variables x and y and assigns the first element of arr to x and the second element of arr to y.
Here is how to swap variables with the array destructuring syntax:
let a = 3;
let b = 5;
[a,b] = [b,a]
// javacript starts to evluate the expression from right to left,
// so first creates an array with elements b, a,
// then assigns to variable a, the first element of the array (in the right side of "=")
// and to variable b, the second elemet of the array
// a === 5, b === 3
Resources:
- book: Algorithms and Programming: Problems and Solutions (Springer Undergraduate Texts in Mathematics and Technology) by Alexander Shen
- Use Destructuring Assignment to Assign Variables from Arrays