The goal is to swap the values of
b. The textbook method for doing this looks something like this:
var a = 1, b = 2, c; c = a; a = b; b = c;
Of course, we've introduced another variable called
c to temporarily store the original value of
a during the swap. But can we do it without
This trick uses an array to perform the swap. Take a second to wrap your head around it:
b = [a, a = b];
There are a few things happening here, so if you're still having trouble understanding how or why this works, I'll explain:
- We're utilizing an array where the first index is the value of
aand the second index is the value of
ais set to the value of
bwhen the array is created
bis set to the first index of the array, which is a
While this trick definitely saves you a few lines of code and a temp variable, be cautious when using it. It's doesn't help that whole code clarity thing.
Want to learn another cool way to swap variables? If you're a math buff, you'll like the xor trick.