If you’re fairly inexperienced with JavaScript but you’ve used jQuery, then its likely you’ve used callback functions. But maybe you don’t fully understand how they work or how they’re implemented.
In this post, which is based on what I’ve learned about callback functions, I’ll try to enlighten you on this fairly common JavaScript technique. And maybe some of our JavaScript experts can chime in and let me know what I’ve omitted or oversimplified.
What is a Callback Function?
The above-linked Wikipedia article defines it nicely:
A reference to executable code, or a piece of executable code, that is passed as an argument to other code.
Here’s a simple example that’s probably quite familiar to everyone, taken from jQuery:
$('#element').fadeIn('slow', function() {
// callback function
});
This is a call to jQuery’s fadeIn() method. This method accepts two arguments: The speed of the fade-in and an optional callback function. In that function you can put whatever you want.
When the fadeIn() method is completed, then the callback function (if present) will be executed. So, depending on the speed chosen, there could be a noticeable delay before the callback function code is executed. You can read more about jQuery’s callback functions here.
How to Write a Callback Function
If you’re writing your own functions or methods, then you might come across a need for a callback function. Here’s a very simple example of a custom callback function:
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}
mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});
Here we have a function called mySandwich and it accepts three parameters. The third parameter is the callback function. When the function executes, it spits out an alert message with the passed values displayed. Then it executes the callback function.
Notice that the actual parameter is just “callback” (without parentheses), but then when the callback is executed, it’s done using parentheses. You can call this parameter whatever you want, I just used “callback” so it’s obvious what’s going on.
The callback function itself is defined in the third argument passed to the function call. That code has another alert message to tell you that the callback code has now executed. You can see in this simple example that an argument passed into a function can be a function itself, and this is what makes callbacks possible in JavaScript.
Here’s a JSBin that uses the simple example above.
Make the Callback Optional
One thing you’ll notice about jQuery callbacks is that they’re optional. This means if a method accepts a callback, it won’t return an error if a callback is not included. In our simple example, the page will return an error if we call the function without a callback, like this:
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}
mySandwich('ham', 'cheese');
You can see this in action here. If you open your developer tools, you’ll see an error that says “undefined is not a function” (or something similar) that appears after the initial alert message.
To make the callback optional, we can just do this:
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
if (callback) {
callback();
}
}
mySandwich('ham', 'cheese');
Now, since we’re checking to ensure the existence of callback, the function call won’t cause an error without it. You can test this example here.
Make Sure the Callback is a Function
Finally, you can ensure that whatever value is passed as the third argument is in fact a proper function, by doing this:
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
if (callback && typeof(callback) === "function") {
callback();
}
}
mySandwich('ham', 'cheese', 'vegetables');
Notice that the function now includes a test using the typeof operator, to ensure that whatever is passed is actually a function. The function call has a third argument passed, but it’s not a function, it’s a string. So the test using typeof ensures no error occurs.
Here’s a JSBin with a nonfunction argument passed as the callback.
A Note About Timing
Although it is true that a callback function will execute last if it is placed last in the function, this will not always appear to happen. For example, if the function included some kind of asynchronous execution (like an Ajax call or an animation), then the callback would execute after the asynchronous action begins, but possibly before it finishes.
Here’s an example that uses jQuery’s animate method:
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
$('#sandwich').animate({
opacity: 0
}, 5000, function() {
// Animation complete.
});
if (callback && typeof(callback) === "function") {
callback();
}
}
mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});
And again here’s that code live.
Notice that although the callback appears later in source order than the animation, the callback will actually execute long before the animation completes. In this case, solving this problem is easy: You just put the callback execution inside the animate method’s callback function (where it says “Animation complete”).
This doesn’t cover all the details regarding asynchronous functions, but it should serve as a basic warning that callback functions will only execute last as long as all the code in the function is synchronous.
Anything to Add?
For most JavaScript junkies, this is probably pretty easy stuff. So forgive me if you were expecting something deeper — this is the best I can do. :) But if you have anything else to add or want to correct anything I’ve said, please do so.

Nice post man!! It’s very useful and important to know how this callbacks works!
Another things on Javascript to know is some Design patterns, look my blog there are some posts about it:
http://www.udgwebdev.com/category/design-patterns/
When I need to wait on multiple animates’ calbacks or ajax requests, inside the function that calls the callback (i.e. mySandwich), I tend to use Deferred objects to sync all those timings. I’ve modified your example to include this: http://jsbin.com/ajigan/edit#preview
excellent !
This deferred thing is another world. I need to read on that! Sounds useful….:S
Ya my head just exploded… thanks for opening this window.
This should also work.
Why complicating…?
I agree. Some people find that type of notation clear, but I don’t. I like to be able to read what something does almost instantly, and that syntax just doesn’t work for me. But I know it does for some people, so that’s their preference, no problem
Does it solve any specific purpose. I think more writing causes more typos and hence more bugs. Please add if it helps more, other than as mentioned in Original Post.
Great write up mate, long time javascript user but never actually figured out how callback methods worked, only recently have I needed to write my own custom callbacks!
Awesome. Was thinkin’ about this just the other day.
I’ve tried this before when I needed it for another project but never managed to get it working. At the time I could only find examples of people adding callbacks to plugins.
This will come in handy in the future and I have booked marked this page for reference! Thanks for such a simple, yet powerful and useful article.
This is a really good writeup. I like that you include the bit about asynchronous calls because that is something that can be maddening until you first begin to understand the concept at work.
One thing you may want to discuss is using a specific method signature with a callback (more often referred to as a delegate, but basically the same thing) to allow for callbacks that take parameters. For example, to receive a more detailed response about the type of sandwich you could do the following:
I think another good example would be how to run a callback that receives arguments and has ‘this’ set to something other than the global object. i.e.:
Thanks for throwing in an example using call/apply!
Your snippet is the best example to understand how
applyworks in Javascript Callbacks.Under “Make Sure the Callback is a Function” you just need to do this
Checking if it’s defined & a function is an extra, unneeded step.
Thanks for the post. Already coming up with ideas to use callbacks in my code. Wish I had read this post 2 projects ago, would have saved me some time.
Great write up mate, long time JavaScript user but never actually figured out how callback methods worked, thanks for shearing!
This looks great and easy. Thanks for the examples. I still have problems implementing it here:
Ive been told that to use value in alert I need something like a callback but I cannot implant it for this…
Don’t use an anonymous function
function(key, value){ alert(“The value for ‘” + key + “‘ is ‘” + value + “‘”); })
but rather a separate stand-alone function
function myAlertFunction(key, value) { alert(“The value for ‘” + key + “‘ is ‘” + value + “‘”); }
which you then call as:
remoteStorage.requestValue(“something”, myAlertFunction(key, value));
Function closure will (should!) guarantee that you see your key/value values.
Thanks a bunch, very useful article :)
I was just looking for the definition of a callback function and I found this! Awesome post!
I just found this, which looks quite relevant to this discussion:
http://callbackhell.com/
Thanks a lot…
This post helped me to understand what callback functions are…
keep up the good work
I am new to javascript world. This was really helpful. thx.
excellent article. Great help to OO developers playing round with JS
Thnx! I learned something today :D
Fantastic work on breaking this all down Louis.
We’ll be sending our newbie JS developers to this page to help them understand the basics of callbacks!
Now, I can use callback in javascript.
Thanks!
Best write-up about callbacks on the net. Ever. Kudos to you.
This thread tells you why:
http://www.codingforums.com/showthread.php?p=1293028#post1293028
Thanks Luke. This page has actually been getting pretty steady traffic via search, and most of the comments here have been pretty positive. Glad everyone likes it.
Excelent article, it helps me a lot!
Much heavier content in this one, but relevant to those considering heavy use of nested callbacks:
http://adamghill.com/2012/12/02/callbacks-considered-a-smell/
Apart from your Post, the best I have seen on callbacks is here”:
http://recurial.com/programming/understanding-callback-functions-in-javascript/
Much obliged for this. Trying to sort out callbacks from the FileReader object. This article was very helpful for that.
Simple but clearly and really great!
Thanks :)
short and sweet……thanks
Just what I was looking for! Jquerymobile refresh listview and selectmenu Need a callback function for this after dynamically creating them. Thanks!
Extremely Helpful !!
Perfect was thinking about this lately and you explained it nicely.
Good Job
It was indeed very helpful for a someone like me who is new to js…..
Many thanks
In javascript, the callback definition you quoted on wikipedia is confusing, I found it gave me the better understanding: “A callback function (in jquery) is executed after the current effect is 100% finished”. in w3schools.
Your callback example is clear and easy to follow, but in practice, it’s the same effect to put all codes in order in a javascript file. For example, I trid to load a css file before showing a form in javascript, I would have the same effect to use callback function you suggested or to put all codes in order without the function. However, the solution is suggested this post “http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file”, binding event onreadystatechange or onload to the callback function. It works for me.
Yes, you’re right, JS lines will load in order of appearance. However, as I understand things, the new lines that run don’t wait for the previous lines to finish. So in some cases (as in the case of a long animated effect like a fade out), you need a callback to ensure the previous code is completely finished before loading the next line.
So while in some cases you can get away with one line after another, there are other cases where you absolutely need the previous code to finish first, in which case you need a callback.
Very easy to understand. Thank you for your informative content.
thanks a lot :)
Very helpful post. Thanks a lot. My understanding of Javascript just went up a notch.
function thankyou(callback) {
alert(‘thank you!’);
callback();
}
thankyou(function() {
alert(‘your the best!’);
}
);
One of the best articles I’ve read. I went from being confused about how to create a callback function to understanding the concept fully in about 20 seconds flat. Thanks :)
Excellent…
Thanks, great information to remind things even if you already read about callback :)
Thank you. I’m fairly new with both JS and JQuery so before reading this post I found callback functions quite magical. :D I keep forgetting to treat functions as objects/variables as well.
Thanks for this introductory lesson, mate
Thank you. Very useful article.