/

How to Return Multiple Values from a Function in JavaScript

How to Return Multiple Values from a Function in JavaScript

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:

1
2
3
const getDetails = () => {
return [37, 'Flavio'];
};

To access the returned values, we can use array destructuring:

1
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:

1
2
3
4
5
6
7
8
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.

tags: [“JavaScript”, “functions”, “array destructuring”, “object destructuring”]