Friday, October 24, 2025
HomeLanguagesJavascriptJavaScript Passing parameters to a callback function

JavaScript Passing parameters to a callback function

In this article, we will see how to pass parameters to a callback function. Firstly let us see what is a callback function.

Callback Function: Passing a function to another function or passing a function inside another function is known as a Callback Function. In other words, a callback is an already-defined function that is passed as an argument to the other code 

Syntax:

function geekOne(z) { alert(z); }
function geekTwo(a, callback) {
    callback(a);        
}
prevfn(2, newfn);

Above is an example of a callback variable in a JavaScript function. “geekOne” accepts an argument and generates an alert with z as the argument. “geekTwo” accepts an argument and a function. “geekTwo” moves the argument it accepted to the function to passed it to. “geekOne” is the callback function in this case. 

Approach: In this, The “GFGexample” is the main function and accepts 2 arguments, and the “callback” is the second one. The logFact function is used as the callback function. When we execute the “GFGexample” function, observe that we are not using parentheses to logFact since it is being passed as an argument. This is because we don’t want to run the callback spontaneously, we only need to pass the function to our main function for later execution. Make sure that if the callback function is expecting an argument. Then we supply those arguments while executing. Moreover, you don’t need to use the word “callback” as the argument name, JavaScript only needs to know it’s the correct argument name. JavaScript callback functions are easy and efficient to use and are of great importance to Web applications and code.

javascript




<script>
    function GFGexample(fact, callback){
    var myFact = "neveropen Is Awesome, " + fact;
    callback(myFact); // 2
    }
      
    function logFact(fact){
    console.log(fact);
    }
    GFGexample("Learning is easy since", logFact);
</script>


Output:

neveropen Is Awesome, Learning is easy since
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS