Can JavaScript Functions Return Multiple Values?
In JavaScript, functions typically return a single value. However, there may be cases where you want to return multiple values.
Using an Array
While JavaScript functions cannot directly return multiple values, you can return an array containing your values. For example:
function getValues() { return [getFirstValue(), getSecondValue()]; }
You can then access the values using destructuring assignment:
const [first, second] = getValues();
This is equivalent to:
const values = getValues(); const first = values[0]; const second = values[1];
Using an Object
Alternatively, you can return an object with named properties for each value:
function getValues() { return { first: getFirstValue(), second: getSecondValue(), }; }
To access the values, use destructuring assignment again:
const {first, second} = getValues();
This is equivalent to:
const values = getValues(); const first = values.first; const second = values.second;
Recommendation
It's highly recommended to use an object instead of an array for returning multiple values. Objects are more descriptive and easier to manage, especially when dealing with larger numbers of values.
The above is the detailed content of How Can JavaScript Functions Return Multiple Values?. For more information, please follow other related articles on the PHP Chinese website!