Comp 110 Swapping

Swapping

When we have two variables and want to swap them, we need to be careful about how we do this. We might try to just take what's stored in variable x and assign it to y, then take what's stored in variable y and assign it to x. This would NOT work! If we want to make a swap, we need to make a new variable to temporarily use to help us out. Let's check out some code to break this down:

let x = 110;
let y = 101;
 
// attempt with just these two variables
x = y; // x is assigned the value 101
y = x; // y is also assigned the value 101

This attempt at swapping with only x and y did not work. We ended up losing 110, which was the original value stored in x, and both our variables ended up storing the value 101! So, now we'll see how using a third variable can help us get the results we want:

let x = 110;
let y = 101;

let temp = x; // temp is assigned the value 110
x = y; // x is assigned the value 101
y = temp; // y is assigned the value 110

This time it worked! We used the temp variable to store the original value of x so we could get it back later after we reassign x ( let temp = x; ). 

Then, we assigned x to hold the value originally stored in y ( x = y; ). 

After that, we wanted to get back our original x value which we put in temp and give it to y. To do this, we assign to hold the value stored in temp ( y = temp; ). 

This successfully performed the swap! started as 110 and ended as 101, and y started as 101 and ended as 110!