Callbacks

Callbacks

Understanding callbacks is essential, they not only provide a means to application flow, but allow you to write cleaner, and more modular code too. You must understand that functions are first class citizens in JavaScript, they can be stored in variables, passed into functions, and returned as a result of an operation. Using a callback is simple, all you need to do is supply an argument into a function, that you will pass data and “call upon” to return that data to the calling function. Sounds complicated, but I promise you its not, have a look at this:

function sayHello(callback) {
    callback("Hello");
};

sayHello(function(greeting) {
   console.log(greeting + ", World!"); 
});

// Output: Hello, World!

As you can see, I’m passing an anonymous function into the callback of my sayHello() function, and greeting gets populated with the callback.

Lets take this example a little further, I’m going to add the ability to say hello in different languages by passing the language in as a parameter, along with the callback.

function sayHello(language, callback) {
    var greetings = {
        "English": "Hello",
        "French" : "Bonjour",
        "German" : "Guten Tag"
    };
    // Return the greeting
    callback(greetings[language]);
};

sayHello("German", function(greeting){
   console.log(greeting + ", World!"); 
});

// Output: Guten Tag, World!

Once again, I invoke our sayHello() function, and pass it an anonymous function, expecting a greeting. However, this time I first pass the language string, to be used as the key in the greetings object. I then callback with the value of the property, which sends the correct greeting back.

Another Example

Have a look at the code below, it creates an object with two callback methods. At the bottom, we invoke those methods and pass those results to a logger function. This example demonstrates how useful callbacks can be, in a more app like structure.

    var callback_examples = {
        // Calls back with a number that is 1-100
        get_randomNumber: function(callback) {
            var randomNumber = Math.floor((Math.random() * 100) + 1);
            // Returns randomNumber to the anonymous function
            callback(randomNumber);
        },
        // Calls back with a name via index
        get_nameByIndex: function(index, callback) {
            var names = [
                "Foo",
                "Bar",
                "Mr.Callback"
            ]
            // Returns the name to the anonymous function
            callback(names[index]);
        }
    };
    
    // Helper function to log the results
    function logResult(functionName, result) {
        console.log("The result of %s is: %s", functionName, result);  
    };
    
    // Call our functions
    callback_examples.get_randomNumber(function(num) { // <-- Anonymous function with the callback
        logResult("get_randomNumber", num);
    });
    
    callback_examples.get_nameByIndex(2, function(name){ // <-- Index along with anonymous function
        logResult("get_nameByIndex", name);
    });

I’ve gone ahead and created a Gist on Github for the code callbacks. Feel free to comment there or below, let me know if you have any questions, or if I misspoke (I’m learning too)!

Link to callbacks Gist here.

Leave a Reply

Your email address will not be published. Required fields are marked *