As we all know to swap two variables we choose to create third variable and then we swap their values like let me show you with example :
var x = 1;
var y = 2;
temp = x;
and then we go further , now here we'll be showing you different methods to swap variables in javascript without making use of third variable.
function swap(value) {
value.first = value.first + value.second;
value.second = value.first - value.second;
value.first = value.first - value.second;
}
// declared an object named value which has two keys - first and second corresponding to the first and the second values respectively
var value = {
first: 1,
second: 2
}
console.log(value.first, value.second) //Prints 1 2
swap(value);
console.log(value.first, value.second); //Prints 2 1
Second Way by creating function again
function swap(x, y) {
return [y, x]
}
var x=1, y=2;
console.log(x+" "+y);
[x, y] = swap(x, y);
console.log(x+" "+y)
Both ways you get the same result
Without Creating function
var x = 1, y = 2;
console.log(x , y)
x = x + y;
y = x - y;
x = x - y;
console.log (x+" "+y); // 2 1
Array destructuring method
var x=1; y=2;
console.log(x,"",y);
[x ,y] = [y ,x];
console.log(x,"",y)
This method will also result you the same result
If you want to return in array format
var x=1; y=2;
console.log(x,"",y) // 1 2
function swap()
{
var t = x;
x = y;
y = t;
return [x , y]
}
console.log(swap(x+" "+y)); //[2 1]
Using bitwise xor operator:
let x = 1, y = 2;
x = x ^ y;
y = x ^ y;
x = x ^ y;
console.log(x ,y);
Top comments (0)