Return multiple values in JavaScript?
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);
No, but you could return an array containing your values:
function getValues() {
return [getFirstValue(), getSecondValue()];
}
Then you can access them like so:
var values = getValues();
var first = values[0];
var second = values[1];
With the latest ECMAScript 6 syntax*, you can also destructure the return value more intuitively:
const [first, second] = getValues();
If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:
function getValues() {
return {
first: getFirstValue(),
second: getSecondValue(),
};
}
And to access them:
var values = getValues();
var first = values.first;
var second = values.second;
Or with ES6 syntax:
const {first, second} = getValues();
* See this table for browser compatibility. Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like Babel.
Since ES6 you can do this
let newCodes = function() {
const dCodes = fg.codecsCodes.rs
const dCodes2 = fg.codecsCodes2.rs
return {dCodes, dCodes2}
};
let {dCodes, dCodes2} = newCodes()
Return expression {dCodes, dCodes2}
is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}
.
This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()
You can do this from ECMAScript 6 onwards using arrays and "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:
var [x, y] = [1, 2];
x; // 1
y; // 2
// or
[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4
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:
let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3
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;