JavaScript | Return multiple values from function
In order to return multiple values from a function, we can not directly return them. But we can return them in form of Array and Object.
Example 1: This example returns the array [“GFG_1”, “GFG_2”] containing multiple values.
<!DOCTYPE html> < html > < head > < title > JavaScript | Return multiple values from function </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "color:green;font-size: 20px;" ></ p > < button id = "GFG_Button" onclick = "returnVal()" > ReturnValues </ button > < p id = "GFG_P" style = "color:green; font-size: 20px;" ></ p > < script > var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_P"); function set(){ return ["GFG_1", "GFG_2"]; } up.innerHTML = set; function returnVal() { down.innerHTML = set(); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: This example returns the object return {Prop_1: “Value_1”, Prop_2: “Value_2” }; containing multiple values.
<!DOCTYPE html> < html > < head > < title > JavaScript | Return multiple values from function </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "color:green; font-size: 20px;" ></ p > < button id = "GFG_Button" onclick = "returnVal()" > ReturnValues </ button > < p id = "GFG_P" style = "color:green; font-size: 20px;" ></ p > < script > var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_P"); function set() { return { Prop_1: "Value_1", Prop_2: "Value_2" }; } up.innerHTML = set; function returnVal() { var val = set(); down.innerHTML = "Prop_1 = " + val['Prop_1'] + "< br >Prop_2 = " + val['Prop_2']; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: