Return multiple values from a function in JavaScript


In this tutorial, we will learn how to return multiple values from a function in JavaScript.

Whenever we call a function in JavaScript it returns only one value using the return statement.

For example:

const personDetail = () =>{
    const name = 'Alex';
    return name;
} 

console.log(personDetail()) // Alex

Now, let's see what happens when we try to return more than one value in the function.

const personDetail = () => {
    const name = 'Alex';
    const address = 'New York';
    return name, address;
} 


console.log(personDetail()) // New York

It will only return the last value of the return statement.

So how do we return multiple values? There are two ways how we can do it, let's see each with an example.

Using Array to return multiple values from a function

First, we can wrap both the return values inside an array like this.

const personDetail = () => {
    const name = 'Alex';
    const address = 'New York';
    return [name, address];
} 

const person  = personDetail()

console.log('Name:',person[0]) // Name: Alex
console.log('Address:',person[1]) // Address: New York

Although this works, it's not a convenient way to access the values of the function using the index of the array.

Or we can use array destructuring to get the values, for example:

const [ name, address ] = personDetail();

console.log(name) // Alex
console.log(address) // New York

Here, both the variables are assigned the value which is returned by the personDetail() call.

Important : The order in which define the const must be equal to the return array.

Using Object to return multiple values from a function

Another way is to return an object containing the values.

Example:

const personDetail = () => {
    const name = 'Alex';
    const address = 'New York';
    return { name, address };
} 


const person  = personDetail()

console.log('Name:',person.name) // Name: Alex
console.log('Address:',person.address) // Address: New York

Here, all the returned values are assigned to the variable person and we can access the values just like we access object properties.

We can also use the object destructuring to access multiple values from the function.

const { name , address } = personDetail()


console.log('Name:', name) // Name: Alex
console.log('Address:', address) // Address: New York

In object destructuring, the values are assigned to the named parameters and we do not have to care about the order we call the values, name and address.

Conclusion: To return multiple values from a function we have to wrap the values in an array or an object. And the best way to call and access those values is to use the object destructuring assignment.


💾 Recommended Articles