If you’re a programmer, you’ve probably heard of functions, which are a set of statements that perform an action and return an output but what are callback functions?

The callback function is an extremely important concept of javascript and is widely used in promises, event listeners, arrays, and much more.

We’ll go over what callback functions are and how to use them in JavaScript in this tutorial as well as We will also talk about the synchronous and asynchronous callback functions. To have clear and profound concepts of Callback functions we will implement some examples as well.

 CallBack Function

A callback function is a function that is first passed as an argument to some other function and needs to be executed after the statements written in that function definition and as the name implies, it is run later within the function. To put it in simple words, a callback function is executed once the current effect is processed.

Syntax for writing a callBack function in JavaScript

The basic syntax is:

function nameFunc(callbackFunc) {


   callbackFunc();

}

This is a ‘nameFunc()’ function that takes a ‘callbackFunc()’ function as an argument. The ‘callbackFunc()’ function is called from within the ‘nameFunc()’ function so it is a callback function indeed.

Example1

Suppose we want to console.log a message after 2 sec.

function message() {


   console.log(“Hello world after 2 seconds”);

}

setTimeout(message, 2000);

The setTimeout() function is a built-in method of JavaScript that takes a timer and a callback function as an argument. Now the message function(a callback function) will only be called and get executed when the timer will expire.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/image1-28.png" data-lazy- height="63" src="data:image/svg xml,” width=”307″>

In the above code, the function message() is passed as an argument and it is called after 2000 milliseconds (2 seconds). Now to relate this to the call back function, the message() function was called after 2 seconds. It wasn’t executed before those 2 seconds. Hence it is a callback function.

Need for callback functions?

You must be thinking why do we even need callback functions. The answer is simple. JavaScript is a sequential or single-threaded language which means it executes sequentially line by line.

JavaScript doesn’t wait for a response before moving on to the next line. It will keep executing and listening for other events or lines of code.

For example:

Example2

Suppose we are logging 1 and 2 from two different functions to the console:

function firstMessage(){


   console.log(“1”);

}

function secondMessage() {


   console.log(“2”);

}

firstMessage();


secondMessage();

Output:

<img alt="" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/image3-26.png" height="94" src="data:image/svg xml,” width=”201″>

As expected, the function firstMessage() is executed first and then the secondMessage() function is executed.

Example3

Suppose that the firstMessage() method comprises an API request to retrieve data from a server. We’ll have to wait for the server’s answer/response hence let’s utilise the built-in method setTimeout once more.

This time we’ll delay the request by 3 seconds to see how we can request an API fetch request.

function firstMessage(){


   //timeout function for delaying request


   setTimeout( function(){


     console.log(“1”);


   }, 3000);


 }

function secondMessage() {


   console.log(“2”);

}

firstMessage();


secondMessage();

In this code, we just moved the console.log(“1”); inside the setTimeout() function.

Now what’s really interesting is that when you run this code,  you’ll see that the 2 will be shown first in the console:

<img alt="" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/image2-27.png" height="64" src="data:image/svg xml,” width=”168″>

After 3 seconds the 1 will be shown:

<img alt="" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/image4-23.png" height="89" src="data:image/svg xml,” width=”119″>

As we can see, the firstMessage() function was called first and then the secondMessage() function was called. However, we cannot see the result in the sequence we called our function.

It’s not that JavaScript did not return our code sequentially, it’s just that JavaScript did not wait for the firstMessage() function to execute completely and started executing the secondMessage() function.

This example was solely put here to show you why we need callback functions. Callback functions let us make sure that some code will not execute until our required code has been executed.

Callback function types

Now that we have seen what callbacks are, how they are used, and why they are important, let’s look at the two types of callback functions.

Synchronous callback function

Synchronous callback functions are run/executed at the same time as the higher-order function which is using the callback function and is mainly blocking; it completes its task then gives the control to another function or line of code.

This is beneficial as suppose you are fetching items from an API. You want your page to load once you fetch some data from an API. Unless the response from the API is fetched, the whole site has to wait.

Example 2 stated above was synchronous functions as it executed line by line and once the first function was executed only then the control was given to the second function i-e secondMessage() function.

Asynchronous callback function

Asynchronous is completely opposite of synchronous as it works parallel with the caller of the function and the call back function. Asynchronous functions are non-blocking as they run or execute later than the higher-order function.

Example 3 provided above was an asynchronous callback function as we called the firstMessage() function but it waited for two seconds. In those two seconds, it gave the control back and the secondMessage() function was executed. Once the three seconds time was up, the firstMessage() function started executing again.

Conclusion

A callback function is a function that is first supplied as an argument to some other function and needs to be executed after the statements written in that function definition. We learned what callback functions are and how to use them in JavaScript, as well as why callback functions are important and what the two types of callback functions are in this post.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/7011409B3A384F43A8417D1DAC68D179-150×150.jpg6165064af0bb2.jpg" height="112" src="data:image/svg xml,” width=”112″>

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.