Sometimes in our JavaScript code, we’ve to swap the values of 2 variables in our code.
In this article, we’ll look at ways to swap 2 variables’ values in JavaScript.
Using Destructuring Syntax
One way to swap the value of 2 variables is to use the destructuring syntax.
For instance, we can write:
let a = 5,
b = 6;
[a, b] = [b, a];
console.log(a, b);
We defined the a
and b
values which are 5 and 6 respectively.
Then in the 3rd line, we use the destructuring to swap their values.
On the right side, we put b
and a
into an array.
Then on the right side, we destructure the array entries by putting a
and b
on .the array on the left side.
So a
is 6 and b
is 5 when we long the values of a
and b
on the last line.
Using a Temporary Variable
We can also use a temporary variable to help swap the values of 2 variables.
To use it, we write:
let a = 1,
b = 2,
tmp;
tmp = a;
a = b;
b = tmp;
console.log(a, b);
We defined a
and b
which are 1 and 2 respectively.
Next, we assign a
to the tmp
temporary variable.
Then we assign b
to a
.
And finally, we assign the tmp
to b
to update b
with the previous value of a
.
Therefore, a
is now 2 and b
is 1.
Conclusion
We can swap the value of 2 variables with JavaScript by using the restructuring syntax or using a temporary variable.