Returning Multiple Values from a Function

JavaScript functions can return a single value only, but there is a work around to return more than two or just return two values from a function JavaScript. For returning multiple values from a function in JS, you need to wrap the return values as elements of an array or return the values as the properties or keys of an object.

Today we will learn about how to return multiple values from a function in JavaScript.

Two ways to return multiple values from a JavaScript function

  1. Using an array
  2. Using an object

Will discuss both of ways to return two values from a function using JavaScript one by one.

1. Using an Array

Let us look at the following example, in this we have used names() function to retrieve the first name and the last name of a person from a database in the backend or from the result of a third-party API call and return the first and the last name in the form of array elements.

<script>
function GetMultipleValuesArray() {
    // return first & last name from the database or API using JS
    let firstName = 'Arpit',
        lastName = 'Mittal';
 
    // return as an array
    return [firstName, lastName];
}
</script>

To return the value use the following syntax:

Traditional Way (non ES6)

const dataArray = GetMultipleValuesArray();
const firstName = dataArray[0];
const lastName = dataArray[1];

Because the dataArray variable is an array, you can refer to its elements using the square brackets array[index].

Here, dataArray is an array variable so, to get its element by accessing the element by it’s index with the above code & syntax.

There is one more way that is, in ES6 we can use destructuring assignment syntax to get the values from an array, for example:

Modern Way (with ES6)

const [firstName, lastName] = GetMultipleValuesArray();

2. Using an Object

For returning the values as an object in JS, you can consider to use following code:

<script>
function GetMultipleValuesObject() {
  let firstName = 'John',
      lastName = 'Doe';
 
  return {
    'firstName': firstName,
    'lastName': lastName
  };
}
</script>

Alternate

We can reduce the above code using object literal syntax extensions in ES6 as follows:

<script>
function GetMultipleValuesObject() {
  let firstName = 'Arpit',
      lastName  = 'Mittal';
 
  return { firstName, lastName };
}
</script>

Returned value as an object can be accessed with below statement:

Traditional Way (non ES6)

const dataObj = GetMultipleValuesObject();
 
const firstName = dataObj.firstName,
    lastName = dataObj.lastName;

We can also unpack properties from an object, we can use the ES6’s object destructuring syntax as follows:

Modern Way (with ES6)

const { firstName, lastName } = GetMultipleValuesObject();

Leave a Comment