JavaScript Return multiple values from function
Last Updated :
11 Jan, 2024
To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.
Below are the approaches used in JavaScript to Return multiple values from a function:
Approach 1: Using Array
The approach of using an array to return multiple values from a JavaScript function involves organizing the values into an array and then utilizing array destructuring to extract and assign those values to individual variables.
Example: This example returns the array [“GFG_1”, “GFG_2”] containing multiple values.
Javascript
function set() {
return [ "GFG_1" , "GFG_2" ];
}
let [x,y] = set();
console.log(x);
console.log(y);
|
Approach 2: Using an object
The approach of using an object to return multiple values from a JavaScript function involves organizing the values into key-value pairs within an object.
Example: This example returns the object return {Prop_1: “Value_1”, Prop_2: “Value_2” }; containing multiple values.
Javascript
function set() {
return {
Prop_1: "Value_1" ,
Prop_2: "Value_2"
};
}
console.log(set);
function returnVal() {
let val = set();
console.log( "Prop_1 = " + val[ 'Prop_1' ]
+ "Prop_2 = " + val[ 'Prop_2' ]);
}
returnVal()
|
Output
[Function: set]
Prop_1 = Value_1Prop_2 = Value_2
Share your thoughts in the comments
Please Login to comment...