Swapping Javascript Variables Without A Third Variable

Last updated: July 30, 2015

While most developers will probably never encounter a situation where they’ll need to swap two integer values without a third variable unless you’re heavily into code golf.

While novel and impractical for most purposes, it can be nice to improve your problem solving skills and learn new things by solving problems without choosing the most obvious solution.

A little bit of trivia: I was actually asked to swap two integer values in a technical interview once-upon-a-time. So you never know if you find yourself going for a front-end development position and you’re asked during the coding test to swap two integer values without a third variable.

Using an array:

var a = 1;
var b = 2;
a = [b, b = a][0];

Simple math:

var a = 1;
var b = 2;
a = a + b; // a = 3 (1 + 2)
b = a - b; // b = 1 (3 - 2)
a = a - b; // a = 2 (3 - 1)

Simple math condensed:

var a = 1; 
var b = 2;
b = (a += b -= a) - b;

Bitwise XOR Swap:

var a = 1;
var b = 2;
a ^= b;
b ^= a;
a ^= b;

ECMAScript 2015 (formerly ES6) Destructuring:
This is my favourite solution of them all. It feels the cleanest, the intent is clearer and it doesn’t rely on any hard to follow math or operators to swap values.

var a = 1;
var b = 2;
[a, b] = [b, a];

 

Dwayne

 

Leave a Reply

Your email address will not be published. Required fields are marked *