What is Callback in JS ?

Callbacks are a great approach to dealing with something once another task has been finished. Here, “something” refers to the execution of a function. Callbacks can be utilized if we wish to run a function immediately following the return of another function.

The type of JavaScript function is objects. They may therefore be supplied as an argument to any other function when calling them, just like any other objects (Strings, Arrays, etc.).

Example : In this example, the add function takes two numbers, adds them, logs the result, and executes a callback function (disp). When calling add(5, 6, disp), it outputs the sum and a message from the callback.

Javascript




// The add() function is
// called with arguments a, b
// and callback, callback
// will be executed just
// after ending of add() function
function add(a, b, callback) {
    console.log(`The sum of ${a}
    and ${b} is ${a + b}`);
    callback();
}
 
// The disp() function is called just
// after the ending of add() function
function disp() {
    console.log(`This must be printed
     after addition`);
}
 
// Calling add() function
add(5, 6, disp)


Output

The sum of 5 
    and 6 is 11
This must be printed
     after addition

Explanation:

Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers.

As a result, the add() is invoked with 1, 2, and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the additional output.

The benefit of Callback:

  • You can run another function call after waiting for the outcome of a prior function call.
  • You can call the parent function from the child function and can also pass data from child to parent.

Promise vs Callback in JavaScript

Similar Reads

What are Promises in JS?

To manage asynchronous actions in JavaScript, promises are used. It is an assurance that something will be done. The promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred....

What is Callback in JS ?

...

Difference:

Callbacks are a great approach to dealing with something once another task has been finished. Here, “something” refers to the execution of a function. Callbacks can be utilized if we wish to run a function immediately following the return of another function....