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 a and b:
var a = 10;
var b = 20;
// Swap a and b
var temp = a;
a = b;
b = temp;
Let's inspect the values of a and b:
Top comments (1)
leave your question in the comment section