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
getValuesfunction returns an array containing three values (1, 2, and 3). - The
valuesvariable 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
getValuesfunction returns an object containing three properties (value1,value2, andvalue3) with corresponding values (1, 2, and 3). - The
valuesvariable is assigned the returned object. - The values in the object can be accessed using the dot notation (e.g.
values.value1for the value of thevalue1property,values.value2for the value of thevalue2property, 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 variablesvalue1,value2, andvalue3. - In the second example, the destructuring assignment
const { value1, value2, value3 } = getValues();extracts the values from the returned object and assigns them to the variablesvalue1,value2, andvalue3.
