JavaScript | Nested functions
Here the task is to create nested functions, JavaScript support nested functions. In the examples given below the output returning is combination of the output from the outer as well as inner function(nested function).
Approach:
- Write one function inside another function.
- Make a call to the inner function in the return statement of the outer function.
- Call it fun(a)(b) where a is parameter to outer and b is to the inner function.
- Finally return the combined output from the nested function.
Example 1: This example using the approach discussed above.
<!DOCTYPE HTML> < html > < head > < title > Nested functions in JavaScript. </ title > </ head > < body id = "body" style = "text-align:center;" > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to call nested function."; function fun1(a) { function fun2(b) { return a + b; } return fun2; } function GFG_Fun() { down.innerHTML = fun1("A Online Computer Science Portal") (" GeeksforGeeks"); } </ script > </ body > </ html > |
Output:
Example 2: This example using the approach discussed above, but here the nested function is created differently than previous one.
<!DOCTYPE HTML> < html > < head > < title > Nested functions in JavaScript. </ title > </ head > < body id = "body" style = "text-align:center;" > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;" > </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to call nested function."; function fun1(a) { fun = function fun2(b) { return a + b; } return fun; } function GFG_Fun() { down.innerHTML = fun1("This is ")("GeeksforGeeks"); } </ script > </ body > </ html > |
Output: