Skip to main content

Command Palette

Search for a command to run...

Callback functions in JavaScript

Published
•6 min read•View as Markdown
Callback functions in JavaScript

Callback functions are probably the most commonly used functional programming technique in JavaScript . Moreover, you can find them in just about every piece of JavaScript code. Yet, they remain mysterious to many JavaScript developers. We will solve this mystery by the end of this article. We will be covering the following details to understand the concept of callbacks in JavaScript:

  • What is a callback function?
  • Why and When to use a callback function in JavaScript?
  • How to use callbacks in JavaScript?

What is a callback function?

A callback, as the name suggests, is a function that is to execute after another function has finished its execution. As we know, in JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can also return functions. "Functions that take the another function" as a parameter are called higher-order functions, and the "function which is passed as an argument" is called a callback function

ho.PNG

Why and When to use callback functions in JavaScript?

We know that in JavaScript, most of the functions are asynchronous, i.e., whenever a user instantiates a function, JavaScript will not wait for its response and will continue its execution of next statements without waiting for the function to complete its execution.

Let's try to understand this situation detail with the help of following code snippet:

     function first(){
        console.log("Inside function: first");
     }

     function second(){
        console.log("Inside function: Second");
     }

     first();
     second();

     //output
     Inside function: first
     Inside function: Second

As per the output, invoking of the functions happens in the mentioned order, i.e., the first() function is invoked and prints its output. Then the second() function invokes and prints its output.

Consider a situation where it is doing some I/O operation or invoking an API, which is taking more time to return the response. JavaScript will continue its execution of the next statements and will not wait for that task to complete its execution.

Example

 function first(){
    // Simulate a code delay
    setTimeout( ()=>{
       console.log("Inside function: first");
       }, 1500 )   
 }

 function second(){
    console.log("Inside function: second"); 
 }

 first();
 second();

//output
Inside function: Second
Inside function: first

So, It's not that JavaScript didn't execute our functions in the order we wanted it to, but it's instead JavaScript didn't wait for a response from first() before moving on to execute second().

So, how do we ensure that the flow and order of execution are as per the developer's expectations? The answer to this is "Callbacks". Which, in turn, ensures that specific code doesn't execute until another code has already finished the execution.

How to use callback functions in JavaScript?

As discussed above, the callback is a function that is passed as a parameter to the other function. In this section, we will cover the details of how callback can be defined and used.

  • How to use named functions as callbacks?
  • How to use anonymous functions as callbacks?
  • Procedure to invoke one callback inside another callback?

How to use named functions as a callback function?

When the callback function uses a "named function", it follows the following syntax:

// Suppose there is function function1(), which should be invoked
// before function2(), then function1() can take a callback as parameter
// which will be invoked as last statement of the function1().


function function1(var1, var2, ....., varN, callback)
{ 
    //Statements to get executed
    callback(var1,var2,var3……,varN);
}

function2(var1, var2,.....,varN)
{   
    //Statements to get executed;
}

// While invoking function1(), pass function2() as parameter
function1(var1,var2,......,varN,function2);

Example:

function first(callback){
    // Simulate a code delay
    setTimeout( function(){
       console.log("Inside function: first");
       callback();
       }, 1500 );
}

function second(){
     console.log("Inside function: second"); 
}

first(second);
// Invokes only first() function, but it invokes second() as well because second() is passed as callback

Procedure to use anonymous functions as callbacks

JavaScript allows passing the "function definition" as the callback parameter directly.

function first(callback) 
{ 
    // Simulate a code delay 
    setTimeout(function()
    { 
          console.log("Inside function: first");
          callback();
      }, 1500); 
} 

first(function()  // Anonymous function passed as callback
{
    console.log("Inside function: second");
});

How to invoke a callback function inside another callback?

Now to take it one step further, apart from using the callback functions inside the functions, we can have "callback function inside another callback function".

While calling the first callback function, we need to pass what should be other callback function values. Its syntax looks like below:

function1(var1,var2,.....,varN,callback1,callback2){

 callback1(var1,var2,var3….,varN,callback2);

}

callBack1(var1,var2,.....,varN,callback2){

 callback2(var1,var2,var3….,varN);

}

callBack2(var1,var2,.....,varN){

 //statements need to get executed

}

funtion1(var1,var2….varN,callBack1,callBack2); 
// Here multiple callbacks are passed as parameters

Let's try to understand it in detail with the help of the following example:

function sumfunc(a, b, callback1, callback2)
{
    console.log("I am in sumfunc function");
    var result = a + b;
    callback1(result, callback2); //callback2 is passed as parameter to callback1
}

function displayfunc(result, callback)
{
    console.log("I am in displayfunc and sum of inputs:"+ result);
    callback(result);
}

function outputfunc(result)
{
    console.log("I am in outputfunc and sum of inputs:"+ result);
}

function CallBackFunction(result) {            
    console.log("I am inside callback function");             
} 

sumfunc(5, 6, outputfunc); //with one callback function

sumfunc(7, 6, displayfunc, CallBackFunction); // with multiple callbacks

So this way, we can chain multiple callback functions to ensure the order of execution for various functions, but this may lead to "callback hell".

What is callback hell?

When you have lots of callback functions in your code! It gets harder to work with them. The more of them you have in your code, and it gets particularly bad to invoke and handle them.

It occurs because, in JavaScript, the only way to delay computation is to put the delayed code inside a callback function, so that it runs after the asynchronous call.

You cannot delay code that we wrote in a traditional synchronous style, so you end up with nested callbacks everywhere. Consider the following example to understand the problem in more detail:

function i_take_10_sec(callback) {
    return setTimeout(() => {
        console.log('I was no: 1 and I take 10 seconds')
        callback()
    }, 10000);
}

function i_take_1_sec(callback) {
    return setTimeout(() => {
        console.log('I was no: 2 and I take 1 second')
        callback()
    }, 1000);
}

function i_take_5_sec(callback) {
    return setTimeout(() => {
        console.log('I was no: 3 and I take 5 second')
        callback()
    }, 5000);
}

function i_take_7_sec(callback) {
    return setTimeout(() => {
        console.log('I was no: 4 and I take 7 second')
        callback()
    }, 7000);
}


function run (){
    i_take_10_sec(()=>{
        i_take_1_sec(()=>{
            i_take_5_sec(()=>{
                i_take_7_sec(()=>{ })
            })

        })
    })
}

run();

Looking at the code above, don't you see that the nested invocation of functions has made the code very difficult to read and understand. This problem is known as a callback hell or the pyramid of doom.

Key Takeaways:

  • When you want one function to execute only after another function has completed its execution, we use callback functions in JavaScript.
  • It needs to pass as a parameter to other functions to make a function callback. The function which accepts the callback as a parameter is known as "High order function".
  • Callback functions can be both a "named function" or an "anonymous function".
  • Callback hell happens when you have multiple callback functions, chained with each other.