For more tips like this, sign up to the weekly newsletter!

Swap variables using the array destructuring operator

Swapping two variables is a typical 0th round technical interview question. It is specifically aimed to immediately disqualify people who have never written code in an imperative language.

The textbook example is, of course, to use a third variable:

var tmp = a;
a = b;
b = tmp;

There are a few unusual and in fact, ingenious solutions you can use if the variables are numbers, like the bitwise XOR method:

a = a ^ b;
b = a ^ b;
a = a ^ b;

But ES6 brought the array destructuring operator, which provides the most readable version of all:

[b, a] = [a, b];

This solution constructs an array with a and b, in this order. Then destructures it in reverse order, so b gets the first value, which is a's, and a gets the second value, which is b's.

How fast is it? Compared to the other methods, it's slow. It constructs an array, assigns the variables, and it leaves some garbage which has to be collected later. But in absolute terms, it's fast, and you shouldn't worry about it.

Now you can ace the 0th step of the technical interview!

Try it
References
Learn more: