I am not able to achieve the desired result for this swap function below, where I want the values printed as 3,2
function swap(x,y){
var t = x;
x = y;
y = t;
}
console.log(swap(2,3));
Any clue will be appreciated !
I am not able to achieve the desired result for this swap function below, where I want the values printed as 3,2
function swap(x,y){
var t = x;
x = y;
y = t;
}
console.log(swap(2,3));
Any clue will be appreciated !
Your function is swapping the values internally, but the function does not return a value.
The following method returns an array of values in reverse order of what was supplied.
function swap(x, y) {
var t = x;
x = y;
y = t;
return [x, y];
}
console.log(swap(2, 3));
However, you could easily do something like the following snippet, because - based on your supplied code - there seems to be no need to actually swap the values of the arguments.
function swap(x, y) {
return [y, x];
}
console.log(swap(2, 3));
If you don't actually need the values to swap:
function swap (x, y)
{
return [y, x];
}
If you do need the values to swap, but you don't want to declare another variable:
function swap (x, y)
{
x = x + y;
y = x - y;
x = x - y;
return [x, y];
}