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
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element and theh1
element have“Click Me”
and“Counter”
asinnerText
respectively. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
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 andh1
element using thedocument.querySelector()
method and stored them in thebtnClick
andcounter
variables respectively. - We have a global variable
count
which has an initial value of 0. - We have attached a
click
event listener to thebutton
element. - We have
myFunction1()
which is responsible for incrementing the value ofcount
by 1 and returning it. - We have
myFunction2()
which takes a callback function as a parameter and sets its returned value asinnerText
of theh1
element. - In the
click
event handler function, we are callingmyFunction2()
and passingmyFunction1()
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(); }