Skip to content

Instantly share code, notes, and snippets.

@ishanbagchi
Created February 12, 2022 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishanbagchi/85a11bae754fe0afa3ab65386878fb7d to your computer and use it in GitHub Desktop.
Save ishanbagchi/85a11bae754fe0afa3ab65386878fb7d to your computer and use it in GitHub Desktop.
Different swapping methods in JavaScript.
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