Can You Return Multiple Values in JavaScript?
Traditionally, JavaScript functions can only return a single value. However, there are ways to simulate returning multiple values.
Array as Return Value
One method is to return an array containing the desired values. For instance:
function getValues() { return [getFirstValue(), getSecondValue()]; }
You can then access the values using destructuring assignment:
const [first, second] = getValues();
This approach is equivalent to:
const values = getValues(); const first = values[0]; const second = values[1];
Object as Return Value
Another option is to return an object with named properties for each value. This provides a more structured and labeled method of returning multiple values:
function getValues() { return { first: getFirstValue(), second: getSecondValue(), }; }
To access the values in this case, you can use the ES6 object destructuring syntax:
const {first, second} = getValues();
Alternatively, you can use the more verbose approach:
const values = getValues(); const first = values.first; const second = values.second;
Recommendation
The recommended approach for returning multiple values in JavaScript is to use an object. This provides clear labeling, ease of adding new values, and better type safety in TypeScript and JSDoc compared to using arrays. Solely return arrays for simple tuples with a clear ordering, such as coordinate pairs [x, y].
The above is the detailed content of How Can I Return Multiple Values from a JavaScript Function?. For more information, please follow other related articles on the PHP Chinese website!