I am trying to return two values in JavaScript. Is that possible?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
I am trying to return two values in JavaScript. Is that possible?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
You can also do:
I would suggest to use the latest destructuring assignment (But make sure it's supported in your environment)
Another worth to mention newly introduced (ES6) syntax is use of object creation shorthand in addition to destructing assignment.
This syntax can be polyfilled with babel or other js polyfiller for older browsers but fortunately now works natively with the recent versions of Chrome and Firefox.
But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it. JavaScript is not best language for developing highly optimal things anyways but if that is needed, you can consider putting your result on surrounding object or such techniques which are usually common performance tricks between JavaScript, Java and other languages.
Other than returning an array or an object as others have recommended, you can also use a collector function (similar to the one found in The Little Schemer):
I made a jsperf test to see which one of the three methods is faster. Array is fastest and collector is slowest.
http://jsperf.com/returning-multiple-values-2
I am nothing adding new here but another alternate way.
You can do this from Javascript 1.7 onwards using "destructuring assignments". Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).
It allows you to assign to 1+ variables simultaneously:
You can also use object destructuring combined with property value shorthand to name the return values in an object and pick out the ones you want:
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
, and3
) sequentially, which eventually evaluates to the value of its last expression —3
. That's whyreturn 1, 2, 3
is functionally identical to nothing more butreturn 3
.