Petter Envall

〈 Back

Switch two values in JavaScript

Feb 07, 2015

This is about switching two values in (pre-ES6) JavaScript without declaring a temporary variable to use in the process. Having this:

var a = 1
  , b = 2; // a==1, b==2

, the simplest way I can think of to switch the values a and b is this:

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

Right? Of course it is slower than using just a temporary variable (see, which is also something one should know about.

In ES6 this can be done simply by something called destructuring assignment, which for arrays looks like this:

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