Solution Review: Juggling Values
Discover how to solve the problem of swapping values between variables in JavaScript without losing data. Learn to use a temporary variable to safely reassign values and ensure all variables retain their correct values after the operation.
We'll cover the following...
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:
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.