The Wayback Machine - https://web.archive.org/web/20220122221301/https://www.geeksforgeeks.org/passing-a-function-as-a-parameter-in-javascript/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Passing a function as a parameter in JavaScript

  • Last Updated : 02 May, 2019

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:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!