jstips icon indicating copy to clipboard operation
jstips copied to clipboard

swapping vars without temp var

Open gk3000 opened this issue 5 years ago • 2 comments

Swapping 2 values without temp variable

TL;DR;

With array destructuring it's really easy to swap two values in a single expression without need of a temporary variable.

let foo = 10, bar = 5;
[foo, bar] = [bar, foo]

That's it, now foo is 5 and bar is 10.

JS first evaluates newly created array on the right of the assignment operator and then destructures it according to the order of vars on the left and since they are the same but in reverse order their values are swapped.

Works for array's items as well:

let foo = [1,2,3,4,5];
[foo[0], foo[4]] = [foo[4],foo[0]]

And objects:

let foo = {a:1,b:2,c:3};
[foo.a,foo.b]=[foo.b,foo.a]

👻

@gk3000

Extra

gk3000 avatar Jan 30 '20 09:01 gk3000

:shipit:

dhbalaji avatar Nov 22 '20 15:11 dhbalaji

@dhbalaji Add tip 75 and add it to the readme.

zenopopovici avatar Dec 06 '21 17:12 zenopopovici