Passing a function as a parameter in JavaScript
Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. Below examples describes to passing a function as a parameter to another function.
Example 1: This example passes a function geeks_inner to the function geeks_outer as an argument.
<!DOCTYPE html> <html> <head> <title> JavaScript | Pass a function as parameter </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> Passing function as arguments. </p> <!-- Function call after clicking the button --> <button onclick = "geeks_outer(geeks_inner)"> Click Here </button> <script> function geeks_inner(value){ return 'hello User!'; } function geeks_outer(func){ alert(func()); } </script> </body> </html> |
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example 2: This example passes a function geeks_inner alongwith a argument ‘Geeks!’ to the function geeks_outer as a argument.
<!DOCTYPE html> <html> <head> <title> JavaScript | Pass a function as parameter </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> Passing function as arguments. </p> <button onclick = "geeks_outer('Geeks!', geeks_inner)"> Click Here </button> <!-- Script to uses function call using function as argument --> <script> function geeks_inner(value){ return 'hello '+value; } function geeks_outer(a, func){ alert(func(a)); } </script> </body> </html> |
Output:
-
Before clicking on the button:
-
After clicking on the button:
Recommended Posts:
- How to set a default parameter value for a JavaScript function ?
- JavaScript | Pass string parameter in onClick function
- How to get the javascript function parameter names/values dynamically?
- JavaScript | Passing parameters to a callback function
- How to add a parameter to the URL in JavaScript ?
- JavaScript | Rest parameter
- HTML | DOM Parameter Object
- How to call a function that return another function in JavaScript ?
- JavaScript | toPrecision( ) Function
- JavaScript | toFixed( ) Function
- JavaScript | Function Invocation
- JavaScript | Math.abs( ) function
- JavaScript | toExponential() Function
- JavaScript | Symbol.for() function
- How to override a JavaScript function ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



