Return multiple values from a function in JavaScript

This tutorial will show you how to return multiple values from a function in JavaScript. A JavaScript function returns only a single value. Multiple values can be returned from a function as array elements by storing those values into elements. We can also return multiple values as properties of objects.

Method 1: By returning an array

We can use an array to return multiple values from a single function. For this purpose, we have to store the values into an array and then return the array that contains all the values.

function codeSpeedy() {
    let name = 'sam',
    let age = 21;

    return [name, age];
}
let getValues = codeSpeedy();
console.log(getValues);

In the above program, I have created a function and declared two variables which are name and age the value of these two variables are sam and 21 which I want to return together from the function.

return [name, age] to store the values of variable name and age into an array.

Then the getValues variable to call the function in the variable.

Output:

[ 'sam', 21 ]

As you can see, the above output is in the array format.

Method 2: By returning an object

In JavaScript, an object can be used to return multiple values from a function as well. For this purpose, we have to store the values as properties of an object.

function codeSpeedy() {
  let name = 'sam',
  let age = 21;

  return {
    name, 
    age
  };
}
let getValues = codeSpeedy()
console.log(getValues);

In the above program, I have stored the values of variable name and age in return statement as properties of an object.

Then called the function in the getValues variable.

Output:

{ name: 'sam', age: 21 }

As you can see, the above output is in the object format.

Leave a Reply

Your email address will not be published. Required fields are marked *