Alternative swapping methods
ES6 only
ES6's new destructuring assignment syntax:
[a, b] = [b, a]
ES5 compatible
There is an universal single line swapping method that doesn't involve creating new temp variables, and uses only an "on-the-fly" array, here it is:
var a = "world", b = "hello";
b = [a, a = b][0];
console.log(a, b); // Hello world
Explanation:
a=b assigns the old value of b to a and yelds it, therefore [a, a=b] will be [a, b]
- the
[0] operator yelds the first element of the array, which is a, so now b = [a,b][0] turns into b = a
Then, for strings only, you can also do this:
var a = "world", b = "hello";
a = b + (b = a, "");
console.log(a, b); // Hello world
You can replace the "" with a 0 if you want to do this with numbers.
Explanation:
(b = a, "") assigns the old value of a to b and yelds an empty string
- now you have
a = b + "", and since that b + "" === b, the old value of b is assigned to a
Performance benchmarks
At this page you can find and run a benchmark of different swapping methods. The result of course varies between browser and JS engine versions.