Swap the values of two given variables.
Swapping the values of two variables is a routine activity in many computer algorithms, especially the ones that perform sorting of arrays.
For instance, if
a = 10 and
b = 20, then after swapping these two variables with one another, we'd get
a = 20 and
b = 10.
In this exercise, you ought to swap the values of the variables
b with one another.
Here's the code to get you started:
var a = 10; var b = 20;
Swapping two variables with one another is an extremely easy task.
We need a temporary variable to hold the value of one variable (let's say
a) while we update that variable (
a) to the other variable (
b, in this case).
Once the first variable (
a) is updated to the second variable (
b), the second variable is updated to the temporary variable.
In the code below, we create this temporary variable
temp, and complete the swapping of
var a = 10; var b = 20; // Swap a and b var temp = a; a = b; b = temp;
Let's inspect the values of
Simple, wasn't this?