How can I return multiple values in JavaScript? I’m trying to return two values from a function, like this:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
Is there a way to do this?
In my experience, one of the simplest ways to return multiple values in JavaScript is by using an array. This way, you group the values together efficiently:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return [dCodes, dCodes2]; // Return as an array
};
// Usage
var codes = newCodes();
var dCodes = codes[0];
var dCodes2 = codes[1];
The approach above keeps things simple and easily accessible by index. Perfect for situations where you just need a quick grouping of values. And there you go—that’s one way to return multiple values in JavaScript.
To add a bit more clarity, you can use an object instead. This way, each value is associated with a clear name, which makes your code more readable:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return { dCodes: dCodes, dCodes2: dCodes2 }; // Return as an object
};
// Usage
var codes = newCodes();
var dCodes = codes.dCodes;
var dCodes2 = codes.dCodes2;
This approach is handy when you want to make sure the values are identified by meaningful keys. Another neat option for how to return multiple values in JavaScript.
Taking it a step further, you can leverage JavaScript’s destructuring assignment to make extracting values even more concise:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return { dCodes, dCodes2 }; // Return as an object
};
// Usage with destructuring
var { dCodes, dCodes2 } = newCodes();
With this approach, you get clear, readable code and quick access to individual properties. It’s definitely one of the cleanest ways to return multiple values in JavaScript, especially if you’re already using objects.