Tag Archives: es6

ES6 Variable Swap Explained

The following ES6 code swaps the values of two variables:

var x = 1;
var y = 2;
[x, y] = [y, x];

It works by using a Destructuring assignment on the array [y, x]. Destructuring is used to extract values from an array or an object. You are able to do this for example:

var [month, year] = [5, 1990]

The example above creates two local variables called “month” and “year” with the respective values 5 and 1990. In the swap example we are omitting the “var” keyword and end up with two simple assignment calls (most ES6 transpilers end up creating the following code):

var x = 1;
var y = 2;
var temp = [x, y];
x = temp[1];
y = temp[0];