Callbacks versus Closures in JavaScript

In my continued goals to get better aquainted with Javascrtipt as well as my readers, today we will discuss two features of JavsScript that confused me for a while and I think I finally got it! They are Closures and Callbacks. Other than both being related to functions, they are quite different in their definition as well as how they are used. In this post, I will try to describe both by example and then explain the differences between them.

Callbacks

Callbacks are nothing specific to JavaScript and neither are Closures. You can use the same knowledge you gain from here and apply it to other languages as well (C# for instance Smile).

Callbacks allow a system to do some sort of work (presumably something that takes a bit of time to complete) and when it returns from doing that work, does this function (callback function). One very common example of this is creating an autocomplete textbox that allows the user to start typing and as they type, the system retrieves data from some data store. Now you don’t want the user waiting all that time while the server returns results and freeze up the UI, so as you probably could have guessed you would use an AJAX call.

Now, lets see what the code for something like this might look like. I am going to assume that you have a working knowledge of JQuery syntax here.

$.ajax({  
           data: 5,    
          url:”/echo/json”,   
          success: function (result) {   
                      alert(‘success’);   
}   });

As you can see above, we have a very simple straight forward AJAX call that calls the JSFiddle API to echo a quick result back to the system. You can pretend that the ‘echo/json’ is returning a list of employee names for a textbox that is being populated using the JQuery autocomplete UI.

The most import part is the success property. This property accepts an anonymous function (I didn’t specifically say callback here for a reason) that will be called upon successful completion of the AJAX call. What makes this a callback function is that it is called after execution of “some code”. The other part that makes this a callback is the fact that the parameter the function accepts is provided by the AJAX function itself. The AJAX success property  passes it’s results from the call directly to the callback.

You can think of a callback as the second part of a handshake. I am not going to say promise here because that means something in JavaScript and I don’t want to get into that. Although as a heads up, this is another place for callbacks. In any case, a callback is the second part of the agreement made between the caller and the object being called that when it finishes doing what you asked it to do, it will also do ‘something else’.

Here is a basic example of creating your own callback that may make a little more sense

// Main function that accepts the callback fn being the callback
function calculator(a, b, fn) {   
// do some internal processing   
return fn(a, b);

// sub functions that are called back to
function sum(a, b) {   
return a + b;
}
function divide(a, b) {  
  return a / b;

var addition = calculator(2, 5, sum);
var d = calculator(10, 5, divide);
alert(“added: ” + addition); alert(“divided: ” + d);

As you can see above, the third parameter being passed to the calculator function is indeed a function. Therefore, you can pass a function into this function that will do some work and then call the function passed in later. To see this in action click here. This is essentially what is done for the Ajax function in JQuery. There are other pieces to it, but this is the basics.

Closures

So now on to closures. Closures are one of the harder things for developers to get that are not primarily functional programmers, but once you get it, there is an AHA moment and it all becomes crystal clear.

The idea of a closure is to allow a function to have access to the variables outside itself. You can almost think of it as a mini global scope between the closure function and it’s parent function. Below is a nice example of creating a generator function that the caller passes in a number and you get something else. This is not a random generator by any means. Just a basic example of what a closure is and how it can be used.

// Main method to generate numbers  
function generateNumber(x) {
    var i = 12;

    // Anonymous function that acts as the closure because it has
    // access to the variables outside itself (i in this case)
    return function () {
        i = i + x;
        alert(“New Number: ” + (i));
    }
}

var b = generateNumber(34);
b();
b();

 

To check out the code live, check it out here. So what you will notice here is that I am calling this generateNumber function and passing in the number 34.  At the beginning of this function, a variable called i is initialized to 12. Under normal “scope” rules, the function in the return statement would NOT have access to this variable because it is not inside the curly braces of that function. This is where the word closure comes in. It closes itself around it’s parent scope and because of this, it has access to the i variable.

Now the function that is returned has nothing passed into it, but has access to the i variable. Because of this, the result will be 46 (12 + 34).

The last thing to note about closures is that they keep a reference to variables even after the parent method completes. Freaky right? So as you can see at the bottom of the code, I call the ‘b’ twice. The first alerts 46, the second alerts 80 (46+34).

Conclusion

So to wrap things up, here is how I view closures and callbacks.

Callbacks are functions that are defined and “used” but executed at some undetermined time. They are often used in returned AJAX calls and events such as a click event to have something happen when the button is clicked.

Closures are inner functions that have access to outer functions variables (enclosing around these functions). A closure also remembers about the variables and environment it as in, so when calling the above method multiple times as we say, it remembers what the ‘I’ variable last was.

I hope this has helped clear it up a bit for some folks. I know it clears it up every time I talk about it a little more each timeSmile

Happy Coding!

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in .NET, .NET 4.5, Best Practices, C#, Classes, Coding standards, Interfaces, JavaScript, JQuery, MVVM, Namespaces, Performance, Programming, Programming Paradims, Web Technologies, Windows Store Apps and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s