Swapping of Two numbers in JavaScript

The value of one variable is assigned to an other and vice versa.

Source code :

//Defining the variables with values
var a=1,b=2;


// swap logic
a = [b][b = a, 0];
 // [b]  - Puts b in an array
 //[b = a,0] - Assign a to b and return  0

// alerting the swapped variables with values
alert("Swapped: a="+a+",b="+b+".");

Output :

Swapped: 2,1.

Notes :

You can also try this traditional method(oldfolks) but the above one is well reformed.

var a = 1;
var b = 2;
a = a + b;
b = a - b;
a = a - b;
alert("Value of a" + a + " and value of b"+b);

Algorithm :

  1. Assign two variables with values
  2. Swap the two numbers using the logic,a = [b][b = a, 0];
  3. Print those swapped variables

Output :


                

Comments :