Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to return multiple values from a function in JavaScript

It wouldn’t sound too obvious but sometimes your function might need to return multiple values. For instance, in one of the applications I’m working on, I have a JavaScript function where I have to calculate two different values and return them.

So, I needed to return two values from the function but there can be an n number of values that can be returned from the function.

Returning array of values

In JavaScript, you can return multiple values from a function using an array. For example, you can do something like this.

const getValues = () => {
    // Do some calculations
    const someValue = 'someValue';

    // Do some other calculations
    const otherValue = 'otherValue';

    return [someValue, otherValue];
};

const allValues = getValues();

console.log(allValues); 
// ['someValue', 'otherValue']

As you can see, the getValues() function returns an array with two values that you can access using the allValues variable.

To make it sweeter, you can destructure the array to get the values.

const getValues = () => {
    const someValue = 'someValue';
    const otherValue = 'otherValue';

    return [someValue, otherValue];
};

const [someValue, otherValue] = getValues();
console.log(someValue); // someValue
console.log(otherValue); // otherValue

The good thing about this is you don’t have to keep the name of the variables the same as the values returned from the function. You can name them whatever you want.

So, the following would work equally well.

const [a, b] = getValues();

console.log(a); // someValue
console.log(b); // otherValue

A real-world example

You might have seen this pattern being used in React. For instance, the useState() hook returns an array with two values like so.

const [isActive, setIsActive] = useState(false);

As you can tell, the first value here is the state and the second value is the function to update the state.

In closing

In this article, we learned how to return multiple values from a function in JavaScript. We saw that you can return multiple values from a function using an array. We also saw that you can destructure the array to get the values.

And this can be useful in many scenarios. For instance, you can use this pattern to return multiple values from a function in React.

If you have any questions, feel free to ask them in the comments below!

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?