Understanding callback functions in Javascript

Callback functions are extremely important in Javascript. They’re pretty much everywhere. Originally coming from a more traditional C/Java background I had trouble with this (and the whole idea of asynchronous programming), but I’m starting to get the hang of it. Strangely, I haven’t found any good introductions to callback functions online — I mainly found bits of documentation on the call() and apply() functions, or brief code snippits demonstrating their use — so, after learning the hard way I decided to try to write a simple introduction to callbacks myself.

Functions are objects

To understand callback functions you first have to understand regular functions. This might seen like a “duh” thing to say, but functions in Javascript are a bit odd.

Functions in Javascript are actually objects. Specifically, they’re Function objects created with the Function constructor. A Function object contains a string which contains the Javascript code of the function. If you’re coming from a language like C or Java that might seem strange (how can code be a string?!) but it’s actually run-of-the-mill for Javascript. The distinction between code and data is sometimes blurred.

// you can create a function by passing the
// Function constructor a string of code
var func_multiply = new Function("arg1", "arg2", "return arg1 * arg2;");
func_multiply(5,10); // => 50

One benefit of this function-as-object concept is that you can pass code to another function in the same way you would pass a regular variable or object (because the code is literally just an object).

Passing a function as a callback

Passing a function as an argument is easy.

// define our function with the callback argument
function some_function(arg1, arg2, callback) {
	// this generates a random number between
	// arg1 and arg2
	var my_number = Math.ceil(Math.random() *
		(arg1 - arg2) + arg2);
	// then we're done, so we'll call the callback and
	// pass our result
	callback(my_number);
}
// call the function
some_function(5, 15, function(num) {
	// this anonymous function will run when the
	// callback is called
	console.log("callback called! " + num);
});

It might seem silly to go through all that trouble when the value could just be returned normally, but there are situations where that’s impractical and callbacks are necessary.

Don’t block the way

Traditionally functions work by taking input in the form of arguments and returning a value using a return statement (ideally a single return statement at the end of the function: one entry point and one exit point). This makes sense. Functions are essentially mappings between input and output.

Javascript gives us an option to do things a bit differently. Rather than wait around for a function to finish by returning a value, we can use callbacks to do it asynchronously. This is useful for things that take a while to finish, like making an AJAX request, because we aren’t holding up the browser. We can keep on doing other things while waiting for the callback to be called. In fact, very often we are required (or, rather, strongly encouraged) to do things asynchronously in Javascript.

Here’s a more comprehensive example that uses AJAX to load an XML file, and uses the call() function to call a callback function in the context of the requested object (meaning that when we call the this keyword inside the callback function it will refer to the requested object):

function some_function2(url, callback) {
	var httpRequest; // create our XMLHttpRequest object
	if (window.XMLHttpRequest) {
		httpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// Internet Explorer is stupid
		httpRequest = new
			ActiveXObject("Microsoft.XMLHTTP");
 	}

	httpRequest.onreadystatechange = function() {
		// inline function to check the status
		// of our request
		// this is called on every state change
		if (httpRequest.readyState === 4 &&
				httpRequest.status === 200) {
			callback.call(httpRequest.responseXML);
			// call the callback function
		}
	};
	httpRequest.open('GET', url);
	httpRequest.send();
}
// call the function
some_function2("text.xml", function() {
	console.log(this);
});
console.log("this will run before the above callback");

In this example we create the httpRequest object and load an XML file. The typical paradigm of returning a value at the bottom of the function no longer works here. Our request is handled asynchronously, meaning that we start the request and tell it to call our function when it finishes.

We’re using two anonymous functions here. It’s important to remember that we could just as easily be using named functions, but for sake of brevity they’re just written inline. The first anonymous function is run every time there’s a state change in our httpRequest object. We ignore it until the state is 4 (meaning it’s done) and the status is 200 (meaning it was successful). In the real world you’d want to check if the request failed, but we’re assuming the file exists and can be loaded by the browser. This anonymous function is assigned to httpRequest.onreadystatechange, so it is not run right away but rather called every time there’s a state change in our request.

When we finally finish our AJAX request, we not only run the callback function but we use the call() function. This is a different way of calling a callback function. The method we used before of just running the function would work fine here, but I thought it would be worth demonstrating the use of the call() function. Alternatively you could use the apply() function (the difference between the two is beyond the scope of this tutorial, but it involves how you pass arguments to the function).

The neat thing about using call() is that we set the context in which the function is executed. This means that when we use the this keyword inside our callback function it refers to whatever we passed as the first argument for call(). In this case, when we refer to this inside our anonymous callback function we are referring to the responseXML from the AJAX request.

Finally, the second console.log statement will run before the first, because the callback isn’t executed until the request is over, and until that happens the rest of the code goes right on ahead and keeps running.

Wrapping it up

Hopefully now you should understand callbacks well enough to use them in your own code. I still find it hard to structure code that is based around callbacks (it ends up looking like spaghetti… my mind is too accustomed to regular structured programming), but they’re a very powerful tool and one of the most interesting parts of the Javascript language.

137 thoughts on “Understanding callback functions in Javascript”

  1. Hei, your article is interesting. I’ve got insight after read this and know a lot more than before about callback function, specifically in JavaScript.
    I did not know that if the function in JavaScript are objects, so I’m glad to know that.
    Thanks :-)

  2. AH! AAAAH! I was searching for a tutorial about callbacks, why they are used and what for. I guess I understood a little bit more now. Thanks!

  3. thanks so much for this. i’ve been searching for a while on a tutorial or an article of sorts to clear up callbacks for me, and this was it. you definitely were not kidding when you said there was nothing out there. thank you!

  4. Hello Everyone,
    We can create function in Java Script to perform some specific task when needed. We can use function in java script to keep some scripts inside it and is used to perform an action on the click event of any object. We can use function keyword to create function in java script………. for more details check this link…… http://mindstick.com/Articles/0864994b-563d-4180-87bd-b6e3bea77c26/?Function%20in%20Java%20Script

    Thanks !!!!!

    1. How does it solve the browser freezing issue? Could you give an example. I ask because having Firefox get frozen while running JavaScript and jQuery seems to be a common occurrence when opening web pages these days. I’d like to be able to run some code to unfreeze it.

  5. Hiya,

    thanks for the article, that cleared up the subject for me, allowing me to properly sequence my functions in collaboration with jquery queue/dequeue functions. Actually, it made the task stupidly simple.

    Seeing as I’d been browsing the net for a solution, finding a jqeury plugin for sequencing functions which I scrapped as being too convoluted, I’m *very* pleased to finally be able to use the callback aspect of js. The concept is familiar as jquery uses it all the time – I’ve just been clueless as to how I can use it myself :)

    As an aside: if you want the callback parameter to be optional you can do a simple ‘if’ in your function:

    if(typeof(callback) === ‘function’)
    callback();

    //Jannik

    1. Not only can you check for typeof === ‘function’ but if it’s exists at all. If undefined then use normal return.

      e.g.

      if ( callback && typeof callback === ‘function’ ) {
      callback.call( this, value );
      } else {
      return value;
      }

      This is roughly how jQuery().html() works and speaking of jQuery, this is how chaining is accomplished for functions that must return a value.

      example:
      var foo = {
      bar1 : function() {
      // do something
      return this; // continue the chain
      },
      bar2 : function( fn ) {
      // do something
      fn.call( this, returnValue );
      return this;
      }
      }

      foo.bar2(function( returnValue ) {
      // alert returnValue
      }).bar1();

  6. Thanks ! That was just what I wanted. I’ve walked on the same route of being a C/Java/PHP dev and I’ve always found it confusing to use callbacks (Though I manage to pull out code with callbacks). I guess it is just a mindstate that fails to comprehend the concept of callbacks and closures.

  7. The first time I read this article I don’t understood it fully because I was at the beginning of js but now it all makes sense :) thank you very much

  8. Thanks for the article, but i have a question
    Why when I run callback functions, func1 is waiting finish func2.

    function func1(arg1, cb1){
    var my_var = arg1;
    cb1(“func1 ready with “+my_var);
    }
    function func2(arg2, cb2){
    var acc = 0;
    for(k=1; k < arg2; k++){
    acc = acc+k;
    }
    cb2("func2 ready with "+acc);
    }

    //Call functions
    func2(100000000, function(resp2){
    console.log(resp2);
    });

    func1(5, function(resp1){
    console.log(resp1);
    });

    Thank again.

    1. Hi again if I put in func2 SetTimeout this is run ok for my, but I dont understand why. can someone help me please.

      function func1(arg1, cb1){
      var my_var = arg1;
      cb1(“func1 ready with “+my_var);
      };
      function func2(arg2, cb2){
      var acc = 0;
      setTimeout(function(){
      for(k=1; k < arg2; k++){
      acc = acc+k;
      };
      cb2("func2 ready with "+acc);
      },0);
      };
      //Call functions
      func2(100000000, function(resp2){
      console.log(resp2);
      });

      func1(5, function(resp1){
      console.log(resp1);
      });

  9. Excellent beginner’s tutorial to callback functions. Thanks for posting this. If you uncover any other Javascript gems worth explaining, I’ll be back to read ‘em!

  10. I recently started learning JavaScript on my own. And I’ve been seeing a lot of callback functions in code examples. I searched the web for a decent tutorial on callback functions but to no avail. Until I came across your blog. I think this is the only tutorial on callback functions. Thank you very much and it is very helpful. Cheers!

  11. Thank you for the comprehensive article. Started on JS yesterday, and although progress is fairly quick, things like this are completely new to me.

  12. hey your page was awesome man … i mean i got the jist of it but …. however could you explain it without ajax…then i guess it would be pretty much simple for those who dunno ajax(me)…:-)

  13. YOU ARE THE MAN!! I’m pretty new to all of this, and only a few weeks old when it comes to .js. Last time I wrote a single line of code (before I started this project), was before basic had a colored screen, and objects only existed in the real-world!

    I’m trying to tidy up the code, now that the race to roll-out is over, and have a ton of code that is essentially duplicated everywhere. A few selector changes allowed me to reduce each block by 75%, and put it in one named function, to be used across the application, but I haven’t been able to get it to return the output object. I spent the better part of the last 24hours, and 50 iterations, looking for an answer, and only found a headache! I’m still not sure why I couldn’t return normally, or why this worked, but I barely had to change what I had left last night, and POW!

    I feel like I owe you a drink or something! THANKS!

  14. Very helpful! I noticed a callback used inside a script found on the web and I was wondering what it meant and now I know :D

    I have very little experience with Java or C, but to me this resembles a bit (but just a bit) to Objective-C’s multithreading techniques, at least on the asynchronous part. There I used to run a method that was doing some heavy computation on a background thread, like parsing an XML in your example, and call a function to update the UI when it finished. I guess the principle is similar

  15. Hello Mike!

    Thank you for sharing an awesome article on callback functions… Now I am able to write code with callback functions…

    Thank you so much!!!

    Mohsin

  16. FINALLY!!!! I was staring to think callbacks were a closely guarded secret or something!
    So much for me is cleared up in your last paragraph:

    “… the second console.log statement will run before the first, because the callback isn’t executed until the request is over, and UNTIL THAT HAPPENS THE REST OF THE CODE GOES RIGHT ON AHEAD AND KEEPS RUNNING.”

    Thanks so much for taking the time to do this, and I hope you do more of these! My only small ‘nark’ here is that you fell into a classic developer habit – only explain what you’re explaining, nothing more. Don’t get distracted by browser compatibility or “.call()” etc… These things are cool, but aren’t in scope with what you’re explaining and just add complexity.

  17. Anyone checked async/await in .NET 4.5? They seem to be a better pattern for asynchronous programming then callbacks. Unfortunately they are not available in JS.

  18. Thanks for the info, seriously.
    Yet, like you, I’ve been writing non-async code too long.
    My mind is not ready for async still! lol

  19. Mike – quick question for you …
    I keep seeing functions represented as ‘callback’ functions in this way:

    x = function() { return $(“iframe”).attr(“src”); };

    … what’s the advantage of this over the ‘standard’ way:

    function x() { return $(“iframe”).attr(“src”); };

    … or even just:

    x = $(“iframe”).attr(“src”);

    ?? It doesn’t wait for the iframe to be present (so it’s not doing anything ‘asynchronously’ … or is it?).

  20. Excellent post, Mike.
    The examples you gave couldn’t have been better. I’ve been wanting take advantage of callbacks in my custom functions beyond jQuery. This article really helps shed light on the subject.

  21. Thanks a lot. We can assume the ‘callback’ function as an assistant of our working function because an assistant is to help us do something.

  22. Excellent Stuff, I appreciate the way to make “callbak” function understanding in a very simple language very much helpful to understand the concept .. good job keep it up Dude! …

  23. Thanks for taking the time to write this out, although I have programmed with JavaScript, I come from the more traditional paradigm.

    It then leaves other questions in my head like… that means you can’t know what it is doing when the callback is running, and asynchronous anarchy :)

    Cheers

  24. This is important, callbacks are *not* asynchronous. AJAX callbacks are asynchronous, because AJAX itself is asynchronous, but callbacks in general are *not*. So callbacks don’t mean your code is non-blocking.

    If you want to do true asynchronous (and therefore non-blocking) code in javascript you need to use web workers, which aren’t supported in IE9 and below:

    http://caniuse.com/webworkers

  25. I cant explain how grateful I am to finally understand the mystery behind these callbacks. This has opened up a new world of javascript for me.

  26. Nice article. Gives a good overview on call back functions to get be started. I definitely agree with you on the ‘Spaghetti’ remark. :)

  27. This article is the first DECENT article ON delegates and callbacks I have come across which MAKES SENSE!!!!

    Keep writing. You rule.

    JTN

  28. Just to clear up something about your intro that I found misleading, the .apply() & .call() methods have nothing to do with “callbacks” per se in JS. There are meant to be used to situationally apply scope. You very briefly went over this, but I felt it was worth noting.

  29. Thank you for taking the time to write this article. I’m just now learning JS and the concept of a callback was new to me. Your explanation cleared it up – mainly that it is used to support asynchronous tasks.

  30. Hi,

    Thanks for this article – it was extremely helpful for me to understand callbacks. I actually do not come across this construct very often. Today it’s actually the first time when I was forced to use it. I was creating a custom callback function for jq boostrap validation – never did it before so started digging for answears.

    Like you, I’m more of a Java/C++ “thinker”. Still, I just got something like a epiphany (positive stroke) after reading this :) SO MANY OPTIONS

  31. Thank you for this article.

    The first time I encountered a callback function in JavaScript, it was a complicated one, which was not a good example for learning callback functions (it was used to learn something else). This article clarifies how callback works in JavaScript for me.

  32. Thank you for this awesome tutorial. I have been trying to understand the difference between return and callback and with simple example that you took in the code cleared my understanding totally. Now I understand the difference between return and callback.

  33. This is the most amazingly simple explanation to a complicated subject I have ever seen. I wish you were my professor! -Thanks

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 class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">