Swap two variables in JavaScript

Swapping two numbers in JavaScript is easy. There are few methods to do it. However, EcamScript 6 standard came up with a better solution which we will see later in this post. Following are the methods.

Method 1: Using third variable

This method is the conventional technique in any programming language. We will create third variable to store one of the variable value.
 var a = 2, b = 3, var c;

 var c = a;
 a = b;
 b = c;

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Method 2: Using the Equation

 var a = 2, b = 3;
 
 a = a+b;
 b = a-b;
 a = a-b;

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Method 3: Using Array

 var a = 2, b = 3;
 
 a = [b, b=a][0];

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Method 4: EcmaScript 6

 var a = 2, b = 3;
 
 [a,b] = [b,a];

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Unknown

Hi! I'm Tirumal and I'm a front-end Developer. I love coding, reading and writing blogs. This blog is all about JavaScript and related technologies. Together, let's make the internet beautiful.

0 comments: