All you need to know about swapping two variables in JavaScript
JavaScript 0 Comments
Swapping two variables normally requires a temporary variable or XOR swap algorithm as shown in example #2. We will learn two types of condition and 5 types of methods of swapping two variables in JavaScript.
1. #2 and #3 examples are valid if the variable is a type of number
2. And the rest of the method valid if the variables are any type like string
, number
, object
, array
etc.
Let’s break down 5 different ways of swapping two variables in JavaScript, Here is the first one.
#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 y
to x
and then tmp
to x
.
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.
The xor operator in JavaScript converts its operands to 32-bit integers (using the
ToInt32
internal 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 withx = "hi"
andy = "there"
, you end up withx == 0
andy == 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][0]; // x = 20 // y = 10
Using array first it will hold the value of x
in 0
position on that array then it will assign the value of y
to 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 x
.
#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
Leave a Reply