1. #2 and #3 examples are valid if the variable is a type of
2. And the rest of the method valid if the variables are any type like
#1 Using a Temp Variable
var x = 10; var y = 20; var tmp = x; x = y; y = tmp; // x = 20 // y = 10
The above method can be used to swap any type of two variables.
In the above example, we created a
tmp variable to hold the value of
x and assign
x and then
Swap variable values without a temporary variable.
#2 Swap using Bitwise XOR operator
var x = 10; var y = 20; x ^= y; y ^= x; x ^= y; // x = 20 // y = 10
To understand this completely please refer to this wiki XOR swap algorithm.
ToInt32internal method—see Section 11.10 of the ECMAScript standard). It does not produce the correct results for non-integer numerical values. It also converts non-numeric values to 32-bit integers. If you start with
x = "hi"and
y = "there", you end up with
x == 0and
y == 0.
#3 Valid only for Numbers
var x = 10; var y = 20; x = x + y; y = x - y; x = x - y; // x = 20 // y = 10
The above example only valid for the variables that are the type of
number. So make sure what you use.
Single Line swapping
Here I’ll show you a couple of methods that can swap any type of variables in a single line.
#4 Using An Array
var x = 10; var y = 20; y = [x, x = y]; // x = 20 // y = 10
Using array first it will hold the value of
0 position on that array then it will assign the value of
x in the second position on that array, then the expression will assign the value of
0 position of array to
y that is actually
#5 Using destructuring expression
Here is my favorite coolest, simplest and readable swapping two variables method using destructuring expression, look at the example below:
var x = 10; var y = 20; [x, y] = [y, x]; console.log(x); // 20 console.log(y); // 10
But be careful it supports only in ES6 and above.
More about destructuring read here