Who You Gonna Call(back)?

In Javascript, callback functions are widely used. But what is a callback function? It’s a function which is passed as an argument to another function.

For example:
myFunc(someArgument, anotherFunc);
In this code, myFunc receives the callback function anotherFunc as an argument. myFunc will run its code, and as soon as it’s complete, it will call anotherFunc. This is the basic idea of a callback. Note that when you pass in anotherFunc as an argument, you do not need to put parentheses – it’s called inside myFunc.

Callback functions are especially useful when dealing with asynchronously getting data. This is something that I came across while using the Google Maps API, where controlling the flow of data is important. For example, if, in the above example, myFunc makes a request for data and is waiting for it, everything will wait for that data to be retrieved, and then, after myFunc is finished, anotherFunc is called. This allows anotherFunc to have access to the data retrieved, and lets you make sure that the data was fully retrieved.

In order to make your own callback function, you simply need to pass in the name of a function as an argument, define it, and call it at some point in the function. Here’s an example:

var callback = function(){
  console.log("Ghostbusters!");
}

function bustGhosts(ghosts, callback){
  for (var i = 0; i < ghosts.length; i++){     ghosts[i].bust();   }   console.log("Who you gonna call?");   callback(); }

If you then call bustGhosts(ghosts,callback);, all the ghosts will be busted, and the console will log "Ghostbusters!" Of course, you could easily pass in another callback function, or even an anonymous function, to have that function called after the ghosts have been busted instead.

You may also like...

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>