JavaScript Return multiple values from function
To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object. This approach allows functions to efficiently produce and deliver diverse sets of values, enhancing flexibility and versatility in JavaScript programming.
Below are the approaches used in JavaScript to Return multiple values from a function:
Table of Content
- Using Array
- Using an object
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.
function set() {
return ["GFG_1", "GFG_2"];
}
let [x,y] = set();
console.log(x);
console.log(y);
Output
GFG_1 GFG_2
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.
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
Contact Us