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
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
a into an array.
Then on the right side, we destructure the array entries by putting
b on .the array on the left side.
a is 6 and
b is 5 when we long the values of
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);
b which are 1 and 2 respectively.
Next, we assign
a to the
tmp temporary variable.
Then we assign
And finally, we assign the
b to update
b with the previous value of
a is now 2 and
b is 1.