Skip to content

Instantly share code, notes, and snippets.

@daniil4udo
Last active June 9, 2019 10:36
Show Gist options
  • Save daniil4udo/0d48d0ebaf8c11dbe6fc0972803ad51b to your computer and use it in GitHub Desktop.
Save daniil4udo/0d48d0ebaf8c11dbe6fc0972803ad51b to your computer and use it in GitHub Desktop.
How swap two values without temporary variables using JavaScript?
// How swap two values without temporary variables using JavaScript?
// Solution only for integers
//1
a = a + b
b = a - b
a = a - b
// or
a += b
b = a - b
a -= b
// Single line swapping with addition
a = b + (b=a, 0)
//3
b=a+(a=b)-b
// Solutions for all types
//4
a = [b, b=a][0];
//ES6
b = (a=>a)(a,a=b);
//or
[a, b] = [b, a]
//ES5
b = (function(a){ return a })(a, a=b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment