DEV Community

disgusting-dev
disgusting-dev

Posted on

How to swap JS variables with destructuring

This swap trick for some reason always borns that phrase in my mind: 'Listen, son, you know there is a couple of techniques for swapping and they look correct, readable etc. - but now Dad will show you the old trick...'

The task is super-simple - just to swap two variables values

Usually it requires some temporal variable as a storage while you do your let a = b;

let a = 1, b = 2, temp = a;

a = b;
b = temp;
Enter fullscreen mode Exit fullscreen mode

So, in ES6 we've got Array Destructuring - simple thing for allocation some array elements as variables in one line of code:

[firstElem, secondElem] = [1, 2, 3, 4]; //variables for 1 and 2
Enter fullscreen mode Exit fullscreen mode

Example above don't require to create the variables before destructuring operation, but on the other hand no one tells it's forbidden:

let a = 1;
let b = 2;

[a, b] = [2, 1];
Enter fullscreen mode Exit fullscreen mode

And that really makes the whole trick, instead of tempo variable, we can use array to place our variables in reversed way:

[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

This is not really just wins you one line of code, but might conceptually be a better solution, when you need to do some other operations with variables

[a, b] = [b, a].map(item => item * 2)
Enter fullscreen mode Exit fullscreen mode

That's it, thank you for reading, the swapping example will play some role in my next articles so consider it small teaser to future posts

Top comments (0)