JavaScript callback

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.

In other words, we can say that a function passed to another function as an argument is referred to as a callback function. The callback function runs after the completion of the outer function. It is useful to develop an asynchronous JavaScript code.

In JavaScript, a callback is easier to create. That is, we simply have to pass the callback function as a parameter to another function and call it right after the completion of the task. Callbacks are mainly used to handle the asynchronous operations such as the registering event listeners, fetching or inserting some data into/from the file, and many more.

Now, let's see how to create a callback by using some illustrations.

It is an example of an asynchronous callback. Asynchronicity can be defined as if JavaScript has to wait to complete the operation and execute the rest of the program during waiting.

Example1

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

Output

JavaScript callback

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.

Example2

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

Output

After the execution of above code, a prompt box will be displayed asking the name of the user -

JavaScript callback

After entering the name, when the user clicks OK, then another prompt box will be displayed asking the amount to be entered -

JavaScript callback

After entering the amount when the user clicks OK, then an alert box will be displayed. It shows the entered user name and amount.

JavaScript callback




Latest Courses