3.10 Exercice: Swapping Variables

Let's end this section with a simple programming exercise, declaring two variables: let a that we're going to define as red and let b that we're going to define as blue. Now when we register them on the console, we're obviously going to get red and blue. So now what I want you to do is write some code here to swap the value of these two varibals. So when we record them to the console, instead of getting red and blue, we're going to get blue and red. So pause the video and spend a few minutes on this exercise and when you're done come back and continue watching the correction. Now to exchange the value of two variables, we need a third variable. So we're going to declare another variable that we're going to call c, we're going to use it as a backup, whatever you're storing in a, we're going to put it in another variable which is c, then we're going to copy b into a, and finally what we have in c which was the value of a before, we're going to copy it into b. So we're going to declare c and set it to a. What we have in a that is red will be copied into c. Now we want to replace a with b. So we have defined an and. The value of b is copied into a. Now these two variables at this point are blue. Finally, we're going to copy what we have with c, which is the original value of a, we're going to copy it to b, we've put b into c. Now when we save the changes, instead of getting red and blue we're going to see blue and red, so that proves that we've exchanged the value of these two variables. That's it for this little exercise at the end of the section on operators in JavaScript. Let's meet again for our next section where we will see the different types of conditional statements in JavaScript.