Heads up! This post was written in 2014, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.
Traditional method #
The goal is to swap the values of
b. The textbook method for doing this looks something like this:
var a = 1; var b = 2; var 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
One-line method #
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.