A complete guide with answers for the interview

Photo by Artem Sapegin on Unsplash

Swapping the value of two variables normally takes three lines and a temporary variable. What if I told you there was an easier way to do this with JavaScript?

There are two types of conditions for such a task. There is the classical condition, where we change two numbers. Then there is the more difficult task — change two of any type (string, float, object, other…).


Traditional Method

The goal is to swap the values of a and b (all types).

let a = 1,
b = 2,
c = 0;
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 c? Yes, we can!


Solution for Integers Only

Let’s start with the first task — to change the two integers.

With mathematical operations

a = a + b
b = a - b
a = a - b

or

a += b
b = a — b
a -= b

XOR

Since these are integers, you can also use any number of clever tricks to swap without using a third variable. For instance, you can use the bitwise XOR operator:

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

or

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

This is called the XOR swap algorithm. Its theory of operation is described in this Wikipedia article. I forgot to mention that this works reliably only with integers. I assumed the integer variables from question’s thread.

Hacks and tricks

Single line swapping with addition

a = b + (b=a, 0)

This solution uses no temporary variables, no arrays, only one addition, and it’s fast. In fact, it is sometimes faster than a temporary variable on several platforms. It works for all numbers, never overflows, and handles edge-cases such as Infinity and NaN.

It works in two steps:

1. (b=a, 0) sets b to the old value of a and yields 0
2. a = b + 0 sets a to the old value of b

Another single line swapping:

b=a+(a=b)-b

Single line swapping with XOR

a = a^b^(b^=(a^b))

Solutions for All Types

And now on to the second task — to change the two variables with any types.

Classic one-line method

This trick uses an array to perform the swap. Take a second to wrap your head around it:

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

There are a few things happening here. If you’re having trouble understanding how or why this works, consider this explanation:

  1. We’re utilizing an array where the first index is the value of a and the second index is the value of b.
  2. a is set to the value of b when the array is created.
  3. b is set to the first index of the array, which is a

Another tricky one-line solution

Using ES6 self executing arrow functions:

b = (a=>a)(a,a=b);

or ES5+ immediately invoked function:

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

ES6+ method

Since ES6, you can also swap variables more elegantly. You can use destructuring assignment array matching. It’s simply:

[a, b] = [b, a]