tags:

views:

40

answers:

3

Hello,

Can I pass a value out of a javascript function and back to the calling function, e.g.

function updateURL(url, name, param) {
  url = url + "&" + name + "=" + param;
}

I want to update url and return the new value.

Is this possible?

+1  A: 
function parentFunction() {
    var url = 'http://www.example.com?qs=1';
    var name = 'foo';
    var param= 'bar';
    var newUrl = updateURL(url, name, param);
}

function updateURL(url, name, param) {
  url = url + "&" + name + "=" + param;
  return url;
}
Dustin Laine
Thanks, but doesn't this just set the return value of the function?I would like to call it like:function parentFunction() { var url = ''; var name = ''; var param= ''; updateURL(url, name, param);}
AJ
Dustin Laine
I see, but what I am trying to find out is does Javascript have "out" parameters or are all parameters "in" parameters?
AJ
I saw you updated your comment, can you expand on what you want. The updateURL function will return a string of the concatenated URL.
Dustin Laine
A: 
var myUrl = updateUrl('url', 'name', 'param');

function updateURL(url, name, param) {
  url = url + "&" + name + "=" + param;
  return url;
}
Fermin
+1  A: 

What you're asking for is called "pass-by-reference". Javascript uses "pass-by-value" for the native types (int, string, etc)---other types are pass-by-reference. For your specific case, I can think of two ways to get what you want. The first is to require callers to pass in an array with a single element and modify that element:

function updateURL(url, name, param) {
    url[0] = url[0] + "&" + name + "=" + param;
}
url = ['http://www.google.com/?'];
updateURL(url, 'foo', 'bar');
alert(url[0]);

The second method would be to use an attribute on an object:

function updateURL(url, name, param) {
    url.url = url.url + "&" + name + "=" + param;
}
url = new Object();
url.url = 'http://www.google.com/?';
updateURL(url, 'foo', 'bar');
alert(url.url);
Zach Hirsch
Ah, I see, not worth the effort really in my case. Thanks.
AJ