Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swapping vars without temp var #436

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

gk3000
Copy link

@gk3000 gk3000 commented Jan 30, 2020

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

@dhbalaji
Copy link

:shipit:

@zenopopovici
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants