Open In App

What is the difference between returning a callback and just calling a callback ?

In programming, a callback function is a function that is passed as an argument to another function, which executes the callback function whenever it requires to do so to complete a certain task. Callback function provides a variety of powerful programming techniques. Callback function makes function execution much more dynamic by allowing what kind of action we want to perform using callback.

Callback function are of two types: synchronous callback (blocking callback) and asynchronous callback (deferred callback).



Now we know what are callbacks and their types, lets see the difference between returning a callback and just calling a callback.

Returning a callback: In returning a callback, the called function returns a callback instead of executing it immediately. The calling code where the callback is returned can execute the returned callback immediately, pass it to some other function and so on. Lets see an example of a function that returns a callback function.






const returnCallbackFunction = () => {
    let i = 10;
    return () => console.log(
        'This is a callback function.\nValue of i is', i
    );
}
 
// A callback function is returned by
// the returnCallbackFunction()
let callbackFunction = returnCallbackFunction();
 
// CallbackFunction is executed
callbackFunction();

Output:

This is a callback function.
Value of i is 10

Calling a callback: In contrast to returning a callback function, calling a callback function is simply the immediate execution of the callback function. Lets see an example of calling a callback function.




// Defining a callback function
const callbackFunction = () => {
    console.log('Calling a callback function');
}
 
// Calling the callback function
callbackFunction();

Output:

Calling a callback function

Article Tags :