DEV Community

Agboola Quadri yomike
Agboola Quadri yomike

Posted on

swapping in js

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:

a == 20
b == 10
Image description

Top comments (1)

Collapse
 
yomtech profile image
Agboola Quadri yomike

leave your question in the comment section