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.
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
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!
Great tutorial, I was looking to implement a callback function and now I can try it.
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!
Thanks! You made it so clear
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 !!!!!
very clear! thank you.
good js project to solve serial callback functions
https://github.com/JacksonTian/eventproxy
Callback methods are widely used in Jquery. It will solve the issue browser freezing while running long scripts.. Anyway thanks for the article.
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.
Nice one …keep it up
Wow! I love this article!! I love you!!! Thanks a lot man! I’ve been using callbacks rather unconfidently, this really helps explain it!
Thank you very much!
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
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();
Very clear@@@@ Was useful and understood it now
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.
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
how can we return a value from a callback function and collect it?? thanx in advance..
Thanks a lot for this article! It made my JavaScript-Day
Nice article – clear, brief and concise
Thanks so much for the clear explanation and example!
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.
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);
});
Excellent Job.
[...] Understanding callback functions in Javascript http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
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!
[...] article on callback functions worked out pretty well and got a positive reaction, so I’m going to continue with the theme [...]
Hey, thanks for the article, that was very useful and easy to understand
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!
its nature of callback function to be asynchronous … it does not block control flow while running.
[...] Understanding callback functions in Javascript http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
Hey thanks for writing this article. Its the clearest tutorial on js callback functions out there
Thank you for the comprehensive article. Started on JS yesterday, and although progress is fairly quick, things like this are completely new to me.
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)…:-)
Great article! Really clears up callbacks… They are so dead straightforward really
You should follow up with a similar style article on prototypes – then do closures!
Thanks man
Very simple and clear article on callbacks.
Very solid article on callback functions. They make a lot more sense to me now.
Brilliant and simple explanation. I use them all the time but now I understand why!
Thanks for this it was really useful for me!
Thanks Mate… Good one.
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!
[...] my code I did the following, using patterns from Recurial and JavaScript Callback after calling [...]
[...] Leverage callbacks [...]
Thanks! That was nice, to the point, and needed!
[...] Loop JavaScript Try…Catch Statement JavaScript Throw Statement Scope in JavaScript Understanding callback functions in Javascript Getting comfortable with Javascript callbacks THE BASICS OF WEB WORKERS Introducing HTML5 [...]
This one is going into my bookmarks. Thank you
[...] http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
Excellent article thanks for taking the time to put it together.
console.log(“this will run before the above callback”);
// this line did the work
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
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
I was wondering about this concept, thanks a lot , your article enlightens my way!
If coming from ruby, callbacks are more like “lambdas” or “procs” which makes function an object.
Thanks it’s all clicked now
[...] http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
[...] http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
Thank you so much!
this was exactly what i was looking for,
good job!!
Easy and right to the point.
Thanks for the explanation man. Definitely helpful.
Great article! JS is _weird_. It is just too… unstructured. Which is kinda cool. Do you have any more articles like this? JS is multi-threaded, right?
Circle me on Google+: https://plus.google.com/115093555862694271963/about/
Follow me on Twitter: https://twitter.com/YatharthROCK
// Internet Explorer is stupid
Ha Love that comment..
Thanks for the article, very insightful.
[...] Understanding callback functions in Javascript [...]
Thanks so much for this. I was struggling with callbacks and you explained it perfectly.
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
Hey
Really good article on callbacks….cheers!
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.
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.
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
[...] messages from the HTML5 WebSocket API Use jQuery to make an AJAX call Wire up an event Implement a callback by using anonymous functions Handle the “this” [...]
[...] Subscribe to RSS December 10, 2012 [...]
Thank you very much for writing this article! Made me instantly able to write my own callback handler…
[...] Understanding callback functions in Javascript. [...]
thanks
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?).
Great Post.
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.
Thank you, after I read your post I found what I was doing wrong.
[...] messages from the HTML5 WebSocket API Use jQuery to make an AJAX call Wire up an event Implement a callback by using anonymous functions Handle the “this” [...]
thanks a lot! this is exactly what i was looking for.
[...] Understanding callback functions in Javascript. [...]
Fantastic explanation! Thanks for this article.
Thanks a lot.
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.
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! …
[...] http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
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
Thanx
Thanks! from java/c++ this is probably the best explanation i got.
Really helpful, thanks!
try to improve your tutorial
Thanks a ton!
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
I should add, user interaction events such as clicks, scrolling etc, as well as timer calls like setTimeout actually *are* asynchronous, but there are some caveats:
http://ejohn.org/blog/how-javascript-timers-work/
Very comprehensive!
Great Post, helped us to figure the details out
Nice one, bro
Hey, thanks! I finally got it.
thnx, best example ever
thanks
This tutorial is really awesome…thanks for the post
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.
Thank You Realy Much :X
It Was Great
[...] http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
[...] (http://recurial.com/programming/understanding-callback-functions-in-javascript) [...]
[...] the end, what I wanted to implement was a JavaScript-ish callback associated with a native App47 Agent call. Alas, it took me a lot of digging to achieve this [...]
[...] http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]
Thank you so much and now I see how callback works!
[...] Understanding callback functions in Javascript (en inglés by recurial.com) [...]
[...] messages from the HTML5 WebSocket API Use jQuery to make an AJAX call Wire up an event Implement a callback by using anonymous functions Handle the “this” [...]
Thanks so much for this! Very informative
Nice article. Gives a good overview on call back functions to get be started. I definitely agree with you on the ‘Spaghetti’ remark.
This article is the first DECENT article ON delegates and callbacks I have come across which MAKES SENSE!!!!
Keep writing. You rule.
JTN
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.
A very well-written article; keep up the excellent work!
[…] Understanding callback functions in JavaScript Link […]
**Thank You**
very clean and easy explanation about callbacks. thanks for the article.
Thanks!
Hey, just another “thanks” for your very clear, concise and well crafted tutorial. Really helped!
RV
[…] http://recurial.com/programming/understanding-callback-functions-in-javascript/ […]
really awesome example and explanation u have here. I become more understand about the nice thing about callback
[…] For more information: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ http://recurial.com/programming/understanding-callback-functions-in-javascript/ […]
Nice article, I always enjoy confirming that I got all the basics right.
Great work. Thank a lot
[…] Source URL: http://recurial.com/programming/understanding-callback-functions-in-javascript/ […]
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.
[…] http://recurial.com/programming/understanding-callback-functions-in-javascript/ […]
[…] How is this possible? Functions in JavaScript are objects created with the Function constructor. The object contains a string. This string is the code of the function. Or something. […]
Nicely composed
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
[…] example, the Chrome extension framework relies very heavily on callback functions, which I had a hard time wrapping my head around as a beginner. The difficulty in grasping tricky […]
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.
Function as an object ! interesting
[…] original thread http://recurial.com/programming/understanding-callback-functions-in-javascript/ […]
Now I understand the callback function, thank you so much!
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.
[…] the whole thing is wrapped in an IIFE, inside of that everything is wrapped in the callback function of an event handler attached to the button, so that all the code is triggered when the button is […]
This is the most amazingly simple explanation to a complicated subject I have ever seen. I wish you were my professor! -Thanks
thanks dude
Un post vraiment plein de bon sens
Thank you so much… Over 3 years old and this post still helped me understand callbacks better than virtually any other I’ve read through.
Very nicely explained..
great explanation about callback.
Super well-written explanation of JS callbacks! Thanks for writing!
[…] Understanding Callback Functions in JavaScript […]
Good work. Thanks for taking the time to write this.
Exactly!
“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…”
[…] explanation of what a callback is in JS and how it […]
[…] asynchronous – if you don’t know what this means, it can be explained better than I can by Michael Vollmer […]
Thank you so much!
[…] to a handle each individual request and return a response. Take a look at Michael Vollmer’s article if you’ve never encountered callback functions in JavaScript. The request received is passed […]
Really nice, clear explanation. Thanks.
Thank you very much! I also come from java background and functions in javascript seemed odd to me. I stumbled on this callback issue and I could not get it. Sending functions as parameters was too hard for me to get.
C’est toujours un plaisir ԁe vous lire
[…] Understanding callback functions in Javascript | Recurial – 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. […]
Hi شركة مكافحة حشرات بالرياض, I succeeded to understand, look:
I will make first example easier to understand:
// 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, go);
function go(num){
console.log(“callback called! ” + num);
}
The line some_function(5, 15, go); calls function some_function(arg1, arg2, callback) {…}. It sends 3 parameters: 2 var + 1 function. arg1 = 5, arg2 = 15, callback = go. Then some_function runs.
Hitting the line: callback(my_number); means calling function go, becasue callback = go. So by this function go runs only after function some_function is completed.
You can also see: http://www.w3schools.com/jquery/jquery_callback.asp