This post will discuss how to return multiple values from a function in JavaScript.

1. Using an Array

We can return an array that contains the multiple values we want to return, and then access them by their index or use the destructuring assignment syntax to unpack them into variables. Here’s an example of how we can achieve this:

Download  Run Code

 
We can use a destructuring assignment to assign multiple values to variables directly from the function call, without explicitly accessing individual elements an array. This saves us from creating intermediate variables. For example, the following code uses the destructuring assignment to unpack values from arrays into corresponding variables.

Download  Run Code

2. Using an Object

Another approach is to return an object that has properties for each value we want to return, and then access them by their property name or use the object destructuring syntax to unpack them into variables. Here’s an example of how we can achieve this:

Download  Run Code

3. Using a Generator

A third option is to return a generator that yields the multiple values we want to return, and then use the next() function or the for…of loop to iterate over the values. Here’s an example of how we can achieve this:

Download  Run Code

That’s all about returning multiple values from a function in JavaScript.