Skip to content

Instantly share code, notes, and snippets.

@ishanbagchi
Created February 12, 2022 08:26
Embed
What would you like to do?
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