JavaScript: Callback
Callback functions is a theory derived from functional programming and specifies the use of functions as arguments.
In JavaScript every function is a first class object, which means that every function is an Object and can be used like any other object. This enables the use of a function as a parameter in another function which is the fundamental idea of callback functions.
PARAMETERS TO CALLBACK FUNCTIONS:
We can also pass parameters to callback functions, just similar to any other function. In the below instance we pass as a parameter the name of the author of the function.
var author = “FF”;
function namedCallback(param){
alert(“namedCallback() called by “+param);
}
function testFunction(callback){
callback();
}
testFunction(namedCallback(author));
MULTIPLE CALLBACK FUNCTION:
Multiple callback functions can be used as parameters of another function.
Var someUlr = …;
function successCallback(){
//success code
}
function completeCallback(){
//complete code
}
function errorCallback(){
//error code
}
$.ajax({
url: someUrl,
success: successCallback,
complete: completeCallback,
error: errorCallback
})
WHY DO WE NEED CALLBACKS?
For one very key reason — JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.
function first(){
console.log(1);
}
function second(){
console.log(2);
}
first();
second();
As the user would expect, the function first is executed first, and the function second is executed second.
// 1
// 2
THE VERDICT
You can now understand what a callback is and how it works. This is just the tip of the iceberg with callbacks, there is still a lot more to learn!