Technoarch Softwares - JavaScript Callback Functions

JavaScript Callback Functions

In JavaScript, features are objects. Because of this, functions can be taken as arguments, and can be returned by means of other functions. Functions that do that are referred to as higher-order features.

How does a callback function work?

An Example :  

function fooGreeting(name) {
alert('Hello ' + name);
}
function fooInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
fooInput(fooGreeting);

 

Here, we have a function fooGreeting which takes a string as a argument, and then alerts the message with the argument concatenated to it.

fooGreeting(Harsh) 
"Hello Harsh"

Then we have another function defined as fooInput which takes callback as an argument


fooInput(fooGreeting)
prompt('Please enter your name.'); 
callback(name);

 
 

Callback Function

 

Is it a pattern? 

It is a Observer pattern. You can think of it as a Publish/Subscribe model. And is easy to implement in "any" programming language.

 

Why use callBack Function?

Callback function are generally used when we are getting a response from the api and need to excute a function when we have the response set or it is received

function Req(query, callback){
  setTimeout(function(){
    var res = query + "Search";
    callback(res);
  },5000);
}

function Results(results){
  console.log("Response from the server: " + results);
}
Req("Server has send the", Results);
// Result in console after 5 second delay:
// Response from the server: Server has send the Search!

 

we make a request to a server. After 5 seconds the response is modified and our callback function Results gets executed.

 

Where can we use callBack Functions?

Callbacks are used for asynchronous operations like – making an request to the Google Maps, fetching/writing data from/into a file, registering event listeners etc. All these use callbacks. This way once the data/error from the operation is returned, the callbacks are used to do something with that inside our code.

Multiple Callback Functions Allowed?

Yes, we can pass more then one callback functions as arguement 

function successCb() {
    // Do stuff if success message received
}

function completeCb() {
    // Do stuff upon completion
}

function errorCb() {
    // Do stuff if error received
}

$.ajax({
    url:"http://technoarchsoftwares.com/favicon.png",
    success:successCb,
    complete:completeCb,
    error:errorCb
});

 

How will Callback functions Help?

They will allow you to

1. DRY - Do not Repeat Yourself 

2. To maintain generic functions

3. To write more specialized functions

4. Easy debug as the code is more readable

 

Conculsion 

JavaScript callback functions are amazing to use as they give extraordinary advantages to web applications and to your code. You should utilize them when the need comes , consistently search for approaches to refactor your code for Readability, Abstraction and Maintainability with callback functions.

 

1 Comments:

  1. I find it useful as it is to the point information, The example used are easy to understand. Thanks for sharing. Looking forward for more such articles.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

Leave a Comments

Your email address will not be published. Required fields are marked *