All you need to know about swapping variables in JavaScript.


let a = 'Hello',
b = 'World';
// TODO: Swap a and b

Destrucutring

We are in 2017 and if you ask a JavaScript developer (who keeps up to date), how to swap two variables. He will probably answer you by telling you about ES6 destructuring :

let a = 'Hello',
b = 'World';
[a, b] = [b, a];
console.log( a + ' ' + b ); // 'World Hello'

And he is right : it’s clear, short and easy to understand.
If you accustomed to python you should even find it very similar to the tuple notation :(a, b) = (b, a) . And this method has the advantage to swap any types of variables : String, Object, Numberor Array. Even if a and b are of different types.

So many benefits, but not without compromise: this method is actually the slowest way to swap two variables ( 40 000 000 operations / seconde ).

The classic on-the-fly Array

Before destructuring, the famous one-liner to swap two variables was :

let a = 'Hello',
b = 'World';
b = [a, a = b][0];
console.log( a + ' ' + b ); // 'World Hello'

A lot of things happen on this magic line :

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

With this method, you can swap any types of variable too. It’s a little bit less readable than destructuring but it’s 33.33% faster ( 60 000 000 operations / seconde ).


Strings

If you are sure your two variables are String , another universal single line swapping method exist :

let a = 'Hello',
b = 'World';
a = b + (b = a, "");
console.log( a + ' ' + b ); // 'World Hello'
  1. (b = a, "") assigns the value of a to b and yelds an empty string.
  2. Now you have a = b + "", and since that b + "" === b, the value of b is assigned to a .

It’s sure, it’s even less readable, but on the performance side it’s 83% faster ( 350 000 000 operations / seconde ) than the previous method.


Numbers

The previous method is easily applicable to numbers :

let a = 1,
b = 2;
a = b + (b = a, 0);
console.log( a === 2 ); // true
console.log( b === 1); // true
  1. (b = a, 0) assigns the value of a to b and add zero;
  2. Now you have a = b + 0, and since that b + 0 === b, the value of b is assigned to a .

Obviously it’s not more readable for the Number that for the String . But for Number it’s blazing fast : 30% faster ( 500 000 000 operations / seconde ) than for String.

Some clever maths

Another well known method to swap two Number it’s to use some clever maths :

let a = 1,
b = 2;
a = a + b; // a == 2 + 1 == 3
b = a - b; // b == 3 - 2 == 1
a = a - b; // a == 3 - 1 == 2
console.log( a === 2 ); // true
console.log( b === 1); // true

The downside of this method is that it’s hard to conceptualize and also takes three lines of code. If we’re already resigned to this swapping method being incomprehensible, is there not a way we can just compact it into a single line? The answer is yes! Just roll the above three lines into one :

let a = 1,
b = 2;
b = (a += b -= a) - b;
console.log( a === 2 ); // true
console.log( b === 1); // true

This method is quite well known but in fact not so fast as that, only 345 000 000 operations / seconde.

XOR swap algorithm

So we stop here? No faster way to swap two Number variables ? Well, there is still one, but there we will clearly forget the readability of the thing :

let a = 1,
b = 2;
a ^= b;
b ^= a;
a ^= b;
console.log( a === 2 ); // true
console.log( b === 1); // true

Three lines ? Too long !!
Ok, what about :

let a = 1,
b = 2;
a ^= b^( b = a);
console.log( a === 2 ); // true
console.log( b === 1); // true

The XOR swap is an algorithm that uses the XOR bitwise operation to swap values of distinct variables having the same data type. “Distinct” means that the variables are stored at different memory addresses; the actual values of the variables do not have to be different. I don’t know if a lot of developers understand it, but one thing it’s sure, it’s the fastest way to swap two Number variables : 515 000 000 operations / seconde.


The unloved method

You know what’s it’s fun ? When we talk about variable swapping, the least sexy and unloved method remains the traditional use of a third temporary variable :

let a = 'Hello',
b = 'World',
c = a;
a = b;
b = c;
console.log( a + ' ' + b ); // 'World Hello'

Why is this method unloved? I don’t really know why, maybe only because it’s not particularly clever. However :

  • It’s easily readable and everybody understand it.
  • You can swap any type of variables: String, Object, Numberor Array. Even if a and b are of different types.
  • And what is most funny is that it’s almost the fastest method, just behind the XOR swap : ~500 000 000 operations / seconde.