0

I've made the following swap function:

function swap(a,b)
{
    var c=b;
    b=a;
    a=c;
}

It is supposed to swap 2 numbers. I have the follwing code:

var x=5;
var y=10;
swap(x,y);

The problem is that when I output the vaues of these variables after swap I still get 5 for x and 10 for y. Any ideas?

cssGEEK
  • 994
  • 2
  • 15
  • 38

1 Answers1

1

Since the parameters are passed by value you cannot write a function that replaces the following:

var a, b;
var temp = a;
a = b;
b = temp;

You can also use a one-liner:

b = [a, a = b][0];
Idos
  • 15,053
  • 14
  • 60
  • 75