How to Pass Function Name as Parameter in Javascript

In this tutorial, you will learn how to pass function name as parameter in javascript. Passing a function is pretty much like passing a variable as a parameter.  The function which is passed as a parameter to another function is generally known as a callback function.

A callback function is invoked inside another function to complete some sort of routine or action and you can also pass arguments to it if it requires some.  Also, a function can take one or more callback functions as parameters.

In the following example, we have a counter and a button. Upon click of a button, we will pass myFunction1() as a callback function to myFunction2() which in turn will increment the counter. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The button element and the h1 element have “Click Me” and “Counter” as innerText respectively.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <button>Click Me</button>
        <h1>Counter</h1>
    </div>
    
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected the button element and h1 element using the document.querySelector() method and stored them in the btnClick and counter variables respectively.
  • We have a global variable count which has an initial value of 0.
  • We have attached a click event listener to the button element.
  • We have myFunction1() which is responsible for incrementing the value of count by 1 and returning it.
  • We have myFunction2() which takes a callback function as a parameter and sets its returned value as innerText of the h1 element.
  • In the click event handler function, we are calling myFunction2() and passing myFunction1() as a parameter.
let btnClick = document.querySelector('button');
let counter = document.querySelector('h1');

let count = 0;

btnClick.addEventListener('click', () => {
   myFunction2(myFunction1);
});


function myFunction1(){
    return count++;
}

function myFunction2(paramFunc){
    counter.innerText = paramFunc();
}