Different swapping methods in 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
var a = 12, b = 24; | |
// destructuring assignment | |
[ a, b ] = [ b, a ]; | |
// addition and difference - 1 | |
a = a + b; | |
b = a - b; | |
a = a - b; | |
// addition and difference - 2 | |
b = a + ( a = b ) - b; | |
// using multiplication and division - 1 | |
a = a * b; | |
b = a / b; | |
a = a / b; | |
// using multiplication and division - 2 | |
b = a * ( a = b ) / b; | |
// bitwise XOR operator | |
a = a ^ b; | |
b = a ^ b; | |
a = a ^ b; | |
// using IIFE | |
a = (function (b) { | |
return b; | |
})(b, b = a) | |
// using temporary variable | |
var temp; | |
temp = a; | |
a = b; | |
b = temp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment