views:

100

answers:

3

I am trying to return two values in javascript
is that possible?

var newCodes = function(){  
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return dCodes, dCodes2;  
};

Thanks

+11  A: 

No, but you could return an array containing your values:

var newCodes = function(){  
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return [dCodes, dCodes2];  
};

Then you can access them like so:

var codes = newCodes();
var dCodes = codes[0];
var dCodes2 = codes[1];

If you want to put "labels" on each of the returned values (so you don't have to remember the number to go along with it), you can return an object:

var newCodes = function(){  
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return {
        'dCodes': dCodes,
        'dCodes2': dCodes2
    };  
};

And to access them:

var codes = newCodes();
var dCodes = codes.dCodes;
var dCodes2 = codes.dCodes2;

This method makes it much easier to maintain if you have a large list of values you need to return. I'd recommend it because the data is much friendlier, but you can always just use an array like above.

musicfreak
Or you can return an object: `return {dCodes : dCodes, dCodes2 : dCodes2};` to make it easier to reference.
Intelekshual
you might even return an object {:dCodes: dCodes, dCodes2: dCodes2}functionally the same but when you reference your returned object you have a bit more readable code as obj.dCodes and obj.dCodes2 vs obj[0] and obj[1]
Jonathan S.
@Intelekshual and @Jonathan: See my edit. :)
musicfreak
+1  A: 

Just return an object literal

function newCodes(){
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return {
        dCodes: dCodes, 
        dCodes2 dCodes2
    };  
}


var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
Sean Kinsey
+4  A: 

You can't do this with standard Javascript (meaning — neither with ECMAScript 3rd nor 5th editions). However, Javascript 1.7 — language extension present in some implementations (e.g. Mozilla) — has so-called "destructuring assignments".

It allows you to assign to 1+ variables simultaneously:

var [x, y] = [1, 2];
x; // 1
y; // 2

// or

[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4

And by the way, don't be fooled by the fact that ECMAScript allows you to return 1, 2, .... What really happens there is not what might seem. An expression in return statement — 1, 2, 3 — is nothing but a comma operator applied to numeric literals (1 , 2, and 3) sequentially, which eventually evaluates to the value of its last expression — 3. That's why return 1, 2, 3 is functionally identical to nothing more but return 3.

return 1, 2, 3;
// becomes
return 2, 3;
// becomes
return 3;
kangax