How to call a function that return another function in JavaScript ?
The task is to call a function which returns another function with the help of JavaScript. we’re going to discuss few techniques.
Approach:
- First call the first function-1.
- Define a function-2 inside the function-1.
- Return the call to the function-2 from the function-1.
Example 1: In this example, “from function 2” is returned from the fun2 which is finally returned by fun1.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Function that return a function. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 19px; font-weight: bold;"> </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to call a function, "+ "which returns the call to another function."; function fun1() { function fun2() { return "From function fun2"; } return fun2(); } function GFG_Fun() { el_down.innerHTML = fun1(); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: In this example, “Alert from fun2” is returned from the fun2 alongwith an alert, Returned value finally returned by fun1.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Function that return a function. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 19px; font-weight: bold;"> </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to call a function, "+ "which returns the call to another function."; function fun1() { function fun2() { alert("From function fun2"); return "Alert from fun2 "; } return fun2(); } function GFG_Fun() { el_down.innerHTML = fun1(); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: