Last active
June 9, 2019 10:36
-
-
Save daniil4udo/0d48d0ebaf8c11dbe6fc0972803ad51b to your computer and use it in GitHub Desktop.
How swap two values without temporary variables using JavaScript?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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