A callback function can be defined as a function passed into another function as a parameter. Don't relate the callback with the keyword, as the callback is just a name of an argument that is passed to a function.
Now, let's see how to create a callback by using some illustrations.
In this example, there are two functions getData( x, y, callback) and showData(). Here, we are calling the getData() with the showData(); that is, we are passing it as the third argument of the getData() function along with two parameters. As a result, the getData() is invoked with the specified parameters, including the callback.
The getData() function display the multiplication of two numbers and once it gets completed the callback function will get executed. In the output, we can see the data of the showData() function gets printed after the output of getData() function.Test it Now
Callbacks are generally used to continue the execution after completing an asynchronous operation - such are referred to as the asynchronous callbacks.
Now, in the next example, we will see a callback which gets immediately executed.
It is another example of using callbacks. It is an example of synchronous callback that gets immediately executed.
Here, there are two functions getData(callback), which takes the input from the user using the prompt box, and the function showData(name, amt), which displays the data entered by the user using the alert dialog box.Test it Now
After the execution of above code, a prompt box will be displayed asking the name of the user -
After entering the name, when the user clicks OK, then another prompt box will be displayed asking the amount to be entered -
After entering the amount when the user clicks OK, then an alert box will be displayed. It shows the entered user name and amount.