Understanding JavaScript Callbacks

Posted on ,56 min read

Prior to understanding what callbacks are, we need to explore functional programming with JavaScript.

Every function in JavaScript is actually an object of Function. The below example helps illustrate.

var add = new Function('a', 'b', 'return a + b');

add(2, 2);
// 4

But functions created explicitly as objects of Function are less efficient than declaring a function normally. (Why?)

If you don’t understand what an object is, stop here and read the wonderful chapter, The secret life of objects from the wonderful book, Eloquent JavaScript.

The fact that functions are objects engenders the possibility of passing and returning of functions by other functions. Let’s look at a few examples.

// can be assigned
var add = function(a, b) { return a + b; }
var anotherAdd = add;
anotherAdd(2, 2); // 4

// can be returned
function addx(x) {
    return function(y) {
        return x + y;
    }
}
var add2 = addx(2);
add2(3); // 5
add2(4); // 6

var add3 = addx(3);
add3(3); // 6
add3(5); // 8

// can be passed
function applyf(f, x, y) {
    return f(x, y);
}

applyf(function(a, b) { return a + b; }, 2, 2); // 4

Conceptually, callbacks are functions that your original function should call once it is done with its work. Below is an amusing analogy that I cartooned to explain this concept better.

Little Nikhil wants his laundry done, but he cannot wait in the laundry shop until the Laundry Chacha is done. Clever little Nikhil gives Laundry Chacha his phone number and Chacha agrees to give Nikhil a callback once he’s done.

In the computing world, functions (Laundry Chacha) accept callbacks as a parameter (Little Nikhil’s phone number) and then proceed to do their work (Laundry). Once the function is complete (Laundry is complete), they call the callback function.

Chacha means uncle in Hindi.

Below is a rough translation of the above concept into JavaScript.

function doLaundry(clothes, callback) {
    // wash the clothes
    // clean the clothes
    // press the clothes
    // whoo, that was a lot of time
    // but now it's done
    // now send back the cleaned clothes to Little Nikhil
    callback(clothes);
}

doLaundry(clothes, function(cleanedClothes) {
    // dress up in the cleanedClothes :-)
});

To conclude, consider the below jQuery example which is often used in the real world.

$.post('/doLaundry', clothes, function(response) {
  // do something
});

This is an example of how clothes is sent as POST data to the server and processed by /doLaundry. The $.post function accepts a callback which it calls on completion of the POST request.