Oleksiy's Blog

Swap variables in JavaScript


A quite common interview question is how to swap two variables w/o creating a third one for that purpose. That's a good one for checking you understanding of core language concepts, rather than best-practice. I'd prefer using intermediate var, rather than violate comprehension.

Array approach

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

or another equivalent one:

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

The claim of not using a var is right here, but technically we create an inline array object in between which lives while the context's active, which can contain more operational overhead than a simple var using.

Closure approach

a = (function (c) { b = a; return c; }(b));

Here we store the intermediate value in lexical scope instead. That's not the best performer either although.

Bitwise approach

If you're dealing with integers and want to make your colleaugues hate you a little bit more, use this:


Let's zoom in:

a = (a = a ^ b, b = a ^ b, a ^ b);

And more zoom:

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

This approach is also known as XOR algorithm.

Arithmetic approach:

a = b + (b=a, 0);

This one is type sensitive. For strings it may look like this:

a = b + (b=a, '');

And less one:


ES6 way

It's just making our live easier:

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