3.10 Exercice: Swapping Variables
Let's close this section with a small programming exercise. We declare two variables, a set to 'red' and b set to 'blue'. Logging them prints red and blue as expected. Your task is to write code that swaps their values so that the console eventually prints blue and red. Pause the video, try it on your own, and then come back for the correction.
Swapping with a temporary variable
To exchange two values you need a third variable to keep a backup, otherwise the first assignment overwrites the value you still need. The classic three-step swap looks like this:
let a = 'red';
let b = 'blue';
let c = a; // save a in c
a = b; // a now holds the value of b
b = c; // b now holds the original value of a (stored in c)
console.log(a); // "blue"
console.log(b); // "red"
- Step 1:
cstores the originala('red'). - Step 2:
ais overwritten withb('blue'). - Step 3:
bis overwritten with the backup inc('red').
That proves the two variables have been swapped. This pattern works in any programming language and is a great way to think about variable assignment. That wraps up this section on operators. In the next one we'll explore the different conditional statements available in JavaScript.