Functions in JavaScript can only return a single value using the return
statement. So, how can we simulate returning multiple values from a function?
When we have the need to return multiple values, we can utilize a couple of tricks to achieve this.
Option 1: Returning an Array
One simple approach is to return an array from the function:
const getDetails = () => {
return [37, 'Flavio'];
};
To access the returned values, we can use array destructuring:
const [age, name] = getDetails();
Now, the age
variable will hold the first value and the name
variable will hold the second value from the array.
It’s important to note that the order in which we define the variables in the destructuring assignment (const [age, name] = getDetails()
) must match the order of values in the returned array.
Option 2: Returning an Object
Another option is to return an object and use object destructuring to extract the values:
const getDetails = () => {
return {
age: 37,
name: 'Flavio'
};
};
const { age, name } = getDetails();
In this case, the order of the properties (age
and name
) in the destructuring assignment doesn’t matter, as long as they match the property names in the returned object.
By returning an object, we can also provide names to each value, making it more expressive and self-explanatory.
Overall, these two techniques allow us to effectively return multiple values from a function in JavaScript.