There may be many different reasons why you'd want to swap two variables be it just changing two item's location in an array or when sorting collections. The traditional way is just define a new variable, assign one value to it, put one of the items in the old place, then put the temp variable back in the new place. But my question is not: is that the only way, rather is it the best for your scenario?
The old way of swapping two variables is done like below:
let x = "Yas"; let y = "Hints"; let temp = x; x = y; y = temp; console.log(x); // Hints console.log(y); // Yas
There is nothing wrong with this approach unless you're doing it frequently.
There is another way you could swap two variables without any temp variable. But this only works with numbers:
let x = 10; let y = 20; x = x + y; y = x - y x = x - y; console.log(x); // 20 console.log(y); // 10
This works two, but now we're doing three additional operations to save some space, so you need to be careful when you use this one. Another thing to consider with this approach is the chance of having overflows with additions or subtractions (
sum should be less than
Number.MAX_SAFE_INTEGER which is
Similar to above approach, you could use
XOR to swap the two variables, but this also works only on numbers:
let x = 3; let y = 5; x = x ^ y; y = x ^ y; x = x ^ y; console.log(x); // 5 console.log(y); // 3
If you're not familiar with
XOR, it works on bits. When you perform
XOR two bits, it evaluates to
1 if they are different, and evaluates to
0 if they're the same.
So let's see why this works.
x = x ^ y
y = y ^ xwhen
x = (x ^ y), so the
y = (x ^ y) ^ ywhich equals to
x ^ (y ^ y) = x ^ 0 = x. So now our
yis the old
x = x ^ ywhen according to our first step
x ^ y, and so
x = (x ^ y) ^ x = y ^ (x ^ x) = y ^ 0 = y.
Is this better than the previous one, probably faster, but still limited to numbers only.
Destructuring is an
ES6 feature which is used a lot in many of the modern frameworks. In its core, it allows you to store array elements in variables.
let x; let y; [x, y] = [1, 2, 3]; console.log(x); // 1 console.log(y); // 2
Now considering how we can use this to swap the elements of an array:
let x = "Yas"; let y = "Hints"; [x, y] = [y , x]; console.log(x); // Hints console.log(y); // Yas
This method is much elegant, but still creates two arrays to perform the swapping. So the efficiency might not be that good if you're swapping many elements.
Just because a feature is available, doesn't mean you should use it in every situation. Think about what is the most important factor in the solution you're implementing. If it's space, choose one which doesn't take much, although it's a bit slower.
If the memory doesn't matter but speed is important, choose accordingly. But definitely consider the situation before deciding on your approach.