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?

1
  • 1
    The values of x and y are passed into swap, not the variables themselves (or a reference to them). Commented May 15, 2016 at 13:44

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

1 Comment

Or just: [a, b] = [b, a] (as of late 2014 (Safari) to mid March 2016 (Chromium))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.