Return Multiple Values from a Function in Javascript
|

Return Multiple Values from a Function in Javascript

JavaScript functions can return a single value using the return statement. To return multiple values, you can use an array or an object to group the values together.

Return multiple values from a function using array

Here is an example using an array:

function getValues() {
  return [1, 2, 3];
}

const values = getValues();
console.log(values[0]); // 1
console.log(values[1]); // 2
console.log(values[2]); // 3
  • The getValues function returns an array containing three values (1, 2, and 3).
  • The values variable is assigned the returned array.
  • The values in the array can be accessed using their indices (e.g. values[0] for the first value, values[1] for the second value, etc.).

Return multiple values from a function using object

You can also use an object to return multiple values:

function getValues() {
  return {
    value1: 1,
    value2: 2,
    value3: 3
  };
}

const values = getValues();
console.log(values.value1); // 1
console.log(values.value2); // 2
console.log(values.value3); // 3
  • The getValues function returns an object containing three properties (value1, value2, and value3) with corresponding values (1, 2, and 3).
  • The values variable is assigned the returned object.
  • The values in the object can be accessed using the dot notation (e.g. values.value1 for the value of the value1 property, values.value2 for the value of the value2 property, etc.).

Use destructuring

You can also use destructuring to extract the values from the array or object when calling the function:

const [value1, value2, value3] = getValues();
console.log(value1); // 1
console.log(value2); // 2
console.log(value3); // 3

const { value1, value2, value3 } = getValues();
console.log(value1); // 1
console.log(value2); // 2
console.log(value3); // 3
  • The destructuring assignment syntax allows you to extract values from an array or object and assign them to separate variables in a single statement.
  • In the first example, the destructuring assignment const [value1, value2, value3] = getValues(); extracts the values from the returned array and assigns them to the variables value1, value2, and value3.
  • In the second example, the destructuring assignment const { value1, value2, value3 } = getValues(); extracts the values from the returned object and assigns them to the variables value1, value2, and value3.

Related articles:

Similar Posts

Leave a Reply

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