In this javascript tutorial we will cover different ways to swap two numbers in javascript. There are different ways to swap numbers. here we will cover them.
- Swap Two numbers using 3rd Temp variable
- Swap Values using Arithmetic Operators
- Swap Values using Destructuring assignment
- Swap Values using Bitwise XOR operator
Swap Two numbers using 3rd Temp variable
<script>
let x = prompt('Enter first value: ');
let y = prompt('Enter second value: ');
//define a temp variable
let temp;
//swap values using temp variable
temp = x;
x = y;
y = temp;
console.log(`Value of x after swapping = ${x}`);
console.log(`Value of y after swapping = ${y}`);
</script>
|
Input:
Enter first value: 12
Enter second value: 24
Output:
Value of x after swapping = 24
Value of y after swapping = 12
Swap Values using Arithmetic Operators
<p>Swap Values using Arithmetic Operators</p>
<script>
let x = parseInt(prompt('Enter first value: '));
let y = parseInt(prompt('Enter second value: '));
// use of basic arithmetic operators
x = x + y;
y = x - y;
x = x - y;
// display the output on the console
console.log(`Value of x after swapping = ${x}`);
console.log(`Value of y after swapping = ${y}`);
</script>
|
- In the above example we taking input values into x and y values
- Then Adding the x, y and assign to variable x
- Now we are subtracting the y value from x, this will return previous x value and assigned to y
- Now subtract current y value from x, this will return x value with swap
Output:
Value of x after swapping = 32
Value of y after swapping = 24
Swap Values using Destructuring assignment
<p>Swap Values using Destructuring assignment</p>
<script>
let x = parseInt(prompt('Enter first value: '));
let y = parseInt(prompt('Enter second value: '));
//apply “destructuring” assignment method
[x, y] = [y, x];
// display the output on the console
console.log(`Value of x after swapping = ${x}`);
console.log(`Value of y after swapping = ${y}`);
</script>
|
Output:
Value of x after swapping = 32
Value of y after swapping = 24
Swap Values using Bitwise XOR operator
<p>Swap Values using Bitwise XOR operator </p>
<script>
let x = parseInt(prompt('Enter first value: '));
let y = parseInt(prompt('Enter second value: '));
// apply the Bitwise XOR operator
x = x ^ y
y = x ^ y
x = x ^ y
// display the output on the console
console.log(`Value of x after swapping = ${x}`);
console.log(`Value of y after swapping = ${y}`);
</script>
|
Output
Value of x after swapping = 32
Value of y after swapping = 24