logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

Callback Functions

Callback functions are passed as arguments of other functions and they are normally executed at the end of the parent function.

We know that Javascript is an asynchronous language and this can be problematic sometimes, like in the example below:

                    

    function get_user(){
        var u = {
            'name': 'John'
        };
        return u;
    }
            
    function greet_user(user) {
        console.log('Hi ' + user.name + ', how are you?');
    }
            
    var user = get_user();
    greet_user(user);

                    
                

In this example we call the get_user() function to retrieve the name of the user, then we use this information in the greet_user() function.

At first, this doesn't seem to be a problem because the get_user function returned the information fast enough, but in a real life situation that information would be retrieved from the database or from an external service which wouldn't be as fast.

To simulate it, let's include a 1 second delay before the first function returns the information.

                    
    
    function get_user(){
        
        window.setTimeout(function(){
            var u = {
                'name': 'John'
            };
            return u;
        }, 1000);
        
    }

                    
                

This time we get an error in the console saying we can't get the name property of an undefined variable. This happens because when we run the greet_user() function, we don't have the info we need yet. We can see that Javascript doesn't wait for the first function to finish before executing the next line.

Since most web applications use external data, that could be a big problem, but with the use of callback functions we can avoid it from happening.

                    

    function get_user(callback){

        window.setTimeout(function(){
            var u = {
                'name': 'John'
            };
            callback(u);
        }, 1000);

    }
            
    function greet_user(user) {
        console.log('Hi ' + user.name + ', how are you?');
    }
            
    get_user(greet_user);

                    
                

Instead of creating the greet_user() function previously, we could create it at the time we call the get_user() function:

                    

    get_user(function (user) {
        console.log('Hi ' + user.name + ', how are you?');
    });

                    
                

Most jQuery methods are based on callback functions:

                    

    $( "#hide" ).click(function() {
        $(".exemplo").hide();
    });

                    
                

The setTimeout method also uses a callback function, which is the first argument:

                    
    
    window.setTimeout(function(){},1000);

                    
                

Contents