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 = "zambiatek Is Awesome, " + fact; Ā Ā Ā Ā callback(myFact); // 2 Ā Ā Ā Ā } Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā function logFact(fact){ Ā Ā Ā Ā console.log(fact); Ā Ā Ā Ā } Ā Ā Ā Ā GFGexample("Learning is easy since", logFact); </script> |
Output:
zambiatek Is Awesome, Learning is easy since



