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;
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
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];
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];
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)
Top comments (0)