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.
Summary
This exercise demonstrates the fundamental technique of swapping two variable values in JavaScript. Students start with two variables assigned string values ('red' and 'blue') and must exchange their contents. The solution introduces a third temporary variable to safely preserve one value during the assignment process, illustrating an essential programming pattern used in sorting algorithms and data manipulation.
Key points
- Declare two variables with initial values to be swapped
- Create a temporary variable to store one value while reassigning the other
- Execute the three-step algorithm: save original value → reassign → restore from temporary storage
- Verify the successful swap by logging both variables to the console
- This pattern is foundational for many programming operations including sorting and data rearrangement
FAQ
Why can't we simply assign one variable directly to the other?
Direct assignment would overwrite the original value before we could save it, causing permanent data loss. A temporary variable ensures both original values are preserved during the exchange.
What is the correct order of operations for swapping?
First, assign the first variable's value to a temporary variable. Second, assign the second variable's value to the first variable. Finally, assign the temporary variable's stored value to the second variable.
How do we confirm the swap was successful?
Use console.log() to print both variables and verify their values are reversed from the original assignment.