Signup/Sign In

Understanding Callbacks in Javascript for Beginners

Posted in Programming   LAST UPDATED: AUGUST 9, 2018

    Javascript is a synchronous language which runs in a single thread. In other words, it cannot multi-task or in simpler words it executes one line of code at a time. It cannot move to the next line of code until the current line has finished executing. If you call a javascript function which is supposed to do some complex processing which will require some time, then for that duration the other parts of your app may freeze as javascript can only handle one on-going task at a moment.

    But with time, as the need for faster applications kicked in, a solution for this problem was presented in the form of callbacks in javascript.


    What is a Callback in Javascript?

    A callback is nothing but a function which is used as an argument or variable in another function. Now you must be wondering why we have to use a function as an argument, well because a function can do a task while an argument/variable can only store a value in it. Let's take a simple example, Your father request you to go to the bank and withdraw a certain amount of money and then use that money to buy grocery for the kitchen. If we were to write it down as pseudocode, we can present it as follows,

    function helpFatherWithBank(account, amount) {
    
        // withdraw 'amount' from the 'account'
    
    }

    Obviously, as we have to use the money to buy grocery, so this function must return the money so that we buy grocery from it, so let's update the function,

    function helpFatherWithBank(account, amount) {
    
        // withdraw 'amount' from the 'account'
    
        return money;
    
    }

    Now we can use this money to buy grocery,

    function buyGrocery(money) {
    
        // we get grocery
    
    }

    In short, we are performing a task, receiving some result/data from it and then we use it to do something else. Callbacks can make this simpler, how? let's see,

    function helpFatherWithBank(account, amount, callback) {
    
        // withdraw 'amount' from the 'account' save it in variable 'money'
    
        // rather than returning the money, we provide it to the callback function to perform the next task
    
        // if callback exists then call the callback
    
        callback && callback(money)
    
    }

    Now, in this case, the function helpFatherWithBank() will be called by passing a callback, in which we can expect the result of the function helpFatherWithBank() and can use it do something else, in our case buy grocery.

    So we will do the following when we call the helpFatherWithBank() function,

    var account = 'XXXXYYYY';
    
    var amount = 500;
    
    helpFatherWithBank(account, amount, function(result) {
    
        // buy grocery with the result
    
    });

    One point to note here is, the functions which accept callback execute the callback after finishing their own execution. And this is how the mechanism becomes asynchronous.

    Confused? it will all make sense soon.




    How a callback makes the function calls asynchronous?

    When we call a normal function which returns a value or an array or an object, in short, it may return anything, then we store the value returned in a variable and then use it to perform some other task.

    But in case of callbacks, we have provided a function as an argument to our main function, which now will not return the value to us, rather provide the result to the callback function to further use it to perform something else.

    So to perform something using the result of a function, we do not have to wait for the function to complete, as we assign another function as a callback to it, which will be called once the main function completes its execution, so we can move onto doing something else.


    Some of you might still be confused, so let's take another real-life example, If you are doing your laundry at a common laundry service in your building basement, and in your building, there is a rule that once the clothes are washed and the owner is not present to switch on the dryer, the nest person in queue can remove the clothes and use the washing machine. In such a situation, you will have to sit there, wait for the clothes to get washed, then switch the machine to the dryer to dry your clothes. You cannot utilize that time for doing something else, rather you have to sit there and wait.

    But what if you can assign a function to the washing machine, that once the clothes are washed, switch the dryer on and start the drying process. In terms of pseudocode, we want the wash() function to provide the result 'washed clothes' to another function dry() to work on the result, and now you are free to do anything while your clothes are washed and dried.

    In these examples, we have only chained two dependent functions, washing and drying clothes, and withdrawing money and using it to buy grocery, but this chain can be infinite, and the execution will continue step by step, while you sit back and relax.

    Same is the case with Javascript. Using callbacks make it efficient as the execution doesn't have to wait for something to finish to do something else.

    I hope this helps the beginners to understand the concept of callbacks, which can be seen almost everywhere in javascript and in its libraries like jQuery etc. If you have any doubt, feel free to comment and we will try to answer them.

    About the author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    Tags:JavascriptCallbackAsync Calls
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS