Let’s swap two numbers a and b in javascript by using temporary variables.
The logic of the code is.
- We will create a temporary variable temp and store the value of a in temp. ( temp = 3 )
- Next, we will store the value of b in a. ( a = 5)
- Finally, we will store the value of temp into b. ( b = 3
var a = 3, b = 5, temp;
temp = a; // temp = 3
a = b; // a = 5
b = temp; // b = 3
console.log(`The number after swaping is ${a} and ${b}`);
The output of the code is
The number after swaping is 5 and 3
Javascript program to swap two numbers without using a temporary variable.
The logic of the code is
- Add a and b and store it in a. ( a = 3 + 5 )
- Next, Subtract b from a and store it in b. ( b = 3 + 5 – 5 = 3 )
- Finally, Subtract b from a and store it in a. ( a = 3 + 5 = 5 )
var a = 3, b = 5;
a = a + b; // a = 3 + 5
b = a - b; // b = 3 + 5 - 5 = 3
a = a - b; // a = 3 + 5 - 3 = 5
console.log(`The number after swaping is ${a} and ${b}`);
The output of the code is
The number after swaping is 5 and 3
Let’s swap two numbers using Javascript deconstructing.
If you feel lazy you can use this method to swap two numbers.
Before reading this code you should know about Javascript deconstructing. I will explain in simple terms.
[a,b,c] = [2,3,5]
2 will be stored in a
3 will be stored in b
5 will be stored in c
Let’s look at our code.
[a,b] =[b,a]
In this case the value of b will be stored in a and value of a will be stored in b.
var a = 3, b = 5, temp;
[a,b] = [b,a];
console.log(`The number after swaping is ${a} and ${b}`);
The output of the code is
The number after swaping is 5 and 3