Understanding Callbacks and Closure in javascript

I'm a JavaScript beginner and just finished reading "JavaScript The good parts". Now, I'm trying to understand and demystify closure and callbacks in JavaScript. Below is a piece of code which I assume should produce numbers from 1 through 10. However the code fails to compile (I'm using node btw).

var someAsyncFn = function() {};
for (var i = 0; i < 10; i++) {
    (function(j) {
        someAsycFn(function() {
            console.log(j);
        });
    })(i);
}

Here is the error log:

        someAsycFn(function() {
        ^
ReferenceError: someAsycFn is not defined

You've made a spelling error:

var someAsyncFn = function() {};
someAsycFn(function() {

Your call to the function omits the letter n.


The reason it doesn't work at all is that this is not real code. It is an example. someAsyncfn is not a real function. It does nothing. var someAsyncFn = function() {}; makes a function that does nothing. It's a placeholder to describe what would happen if there was a real asynchronous function.

Something like this would show the effect in a web browser (you'd need to use a different asynchronous function in node.js; I'm using jQuery to keep the code clean).

var someAsyncFn = function(successfn) {
    $.get(document.location, successfn); // make an AJAX request to the current URL, for demonstration purposes
                                         // successfn will be called when the request succeeds
};
for (var i = 0; i < 10; i++) {
    (function(j) {
        someAsyncFn(function() {
            console.log(j);
        });
    })(i);
}

This works because (a) the function containing console.log is now actually called and (b) because it is called asynchronously, when the $.get request is complete.

The whole point of this is that the code runs asynchronously, which means you won't get 0 to 9 in order; you'll get them in the order that the requests completed. For me, this was:

2
3
1
0
4
5
6
7
8
9

You will probably get a different result.