Short JavaScript notes and small code examples.
Swapping values
Cheat sheet
✍️ swap(a, b) moves the value from a to b and from b to a
✍️ The standard approach uses three variables
✍️ A trickier approach can do it with two variables
Lecture
So far we only assigned values to variables, and it might seem there is nothing interesting to do. But there is a classic task: how to swap the values of two variables. This is an important part of sorting algorithms. Think about it. You have two variables:
let a = 5, b = 8;
...
console.log("a=", a, "b=", b);
Your task is to insert code instead of ... so the output is a=8, b=5. Of course, the solution should be generic and based on assignments between variables. Note that a = b or b = a immediately breaks the problem because one value is lost. You can avoid this trap by introducing a third variable. Try writing your own program and testing it in the browser console.
The resulting code is the well-known swap function used in many libraries. A harder and less common task is swapping without a third variable. That is where operations other than plain assignment become useful.
If you get stuck, check our GitHub: three, minus, and xor. You can also play with our "ref" swap simulator.
#education #devJS #devTopic #junior
