Discussion on the solution to the problem "Juggling Values" in this lesson.
Solution
The solution to this problem relies on copying the value of at least one variable into another temporary variable. After that, we can start mutating variables. The illustration below shows what happens if you approach this problem naively.
As you can see above, directly assigning values to the respective variables leads to one unsatisfied variable. So how can you prevent this?
The answer is pretty simple. We declare a new temporary variable to store the value of the first reassigned variable. This way, we can easily solve the problem.
Using a temporary variable named “temp,” assign the value of the first reassigned variable, which in our case is “var1”. By the end of the process, we won’t lose any value access. This will eventually solve the problem and deliver the desired answer. The below code demonstrates this:
var var1=20; // initialize the value of var1 with 20var var2=30; // initialize the value of var2 with 30var var3=10; // initialize the value of var3 with 10console.log("Original Values:");console.log(`var1:${var1}, var2:${var2}, var3:${var3}`); // print values// Solution is belowvar temp = var1; // store var1 value temoporaryvar1= var3; // overwrite var1 with var3var3= var2; // overwrite var3 with var2var2= temp; // overwrite var2 with temp (old var1 value)console.log("New Values:");console.log(`var1:${var1}, var2:${var2}, var3:${var3}`); // print values
Looking at the code, the first action is to initialize a variable and assign the initial value being done in line 8. We create a variable named temp
and assign it the value of var1
. Once done, we mutate var1
to the correct value which, in this problem, is assigned to var3
(line 9). Consequently, we do the same for var3
and reassign to its target value, assigned to var2
(line 10). Finally, we assign the correct value for var2
(line 11), which we initially assigned to temp
.