Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple values in JavaScript?

I am trying to return two values in JavaScript. Is this possible?

var newCodes = function() {       var dCodes = fg.codecsCodes.rs;     var dCodes2 = fg.codecsCodes2.rs;     return dCodes, dCodes2; }; 
like image 310
Asim Zaidi Avatar asked May 26 '10 22:05

Asim Zaidi


People also ask

Can you return multiple values JavaScript?

Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.

How can I return multiple values?

You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas.

How do I return multiple values in TypeScript?

To return multiple values from a function in TypeScript, group the values in an array and return the array, e.g. return [myValue1, myValue2] as const . You can then destructure and use the values the function returns. Copied! We declared a function that returns multiple values by grouping them in an array.


1 Answers

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.

like image 194
Sasha Chedygov Avatar answered Sep 25 '22 08:09

Sasha Chedygov