Passing a function as a parameter in JavaScript
In this article, we will pass a function as a parameter in Javascript. Passing a function as an argument to the function is quite similar to passing a variable as an argument to the function. so variables can be returned from a function.
The below examples describe 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.
html
< 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 > |
Output:

Example 2: This example passes a function geeks_inner along with an argument ‘Geeks!’ to the function geeks_outer as an argument.
html
< 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 > |
Output:

Example 3: Here in this example, a smaller function is passed as an argument in the sayHello function. so here actually we are passing a smaller function address to the function sayHello.
Javascript
<script> function sayHello(param){ console.log( "hello" ,param); param(); return "Hiii Geeks for Geeks" } //function address function smaller(){ console.log( "Is everything alright" ) } //function call const returnHello= sayHello(smaller) console.log(returnHello) </script> |
Output:
hello Ć’ smaller(){ console.log("Is everything alright") } Is everything alright] Hiii Geeks for Geeks
Please Login to comment...