logo

Petter Envall

Notes
2015
February
07
switching-values-in-javascript

Switch two values in JavaScript

(
  • javascript
  • tricks
  • variables
)
2015-02-07

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]; // b==2, a==1

Right? Of course it is slower than using just a temporary variable (see http://jsperf.com/variable-switch), 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]; // b==2, a==1