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; };
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With