JS Callback function

·

1 min read

A Callback Function is A funcion passed outsiide another function as an argument which then called inside another function to call some routine or name

The function in which the the parameter is an argument is called callback function the calling function is higher order function

image.png

          /*define a function to add two numbers*/
             function do_sum(num1, num2)
             {
               var sum = 0;
               /*delay execution for 1 second*/
               setTimeout(function(){
                 sum = num1 + num2;
               }, 1000);
               return sum;
             }

             var sum = do_sum(10, 20);
             document.write(sum);

javascript is a synchronus language which means code runs top down order but sometimes code runs asynchronsly using setTimeOut or await methods due to which code sometimes do not run according to logic above function output will be zero because since do_sum is a method which calculates sum after 1 sec so the value of sum remains 0

                function do_sum(num1,num2,callback)
                {
                var sum=0;

                setTimeout(function(){
                sum=num1+num2;
                callback(sum);  
                },3000
                );

                }

                var sum= do_sum(10,20,function(result){
                document.write(result);
                });

function(result){ document.write(result) }) is the callback parameter that is being overidden this will throw correct result

      console.log('setTimeout() starts');

      setTimeout(function later() {
        console.log('later() is called');
      }, 2000);

      console.log('setTimeout() completed');

later() is an asynchronous callback because setTimeout(later, 2000) starts and completes its execution, butlater() is executed after passing 2 seconds. Try the demo.