Friday, April 10, 2020
Home Javascript What is a Callback Function and How to use it

What is a Callback Function and How to use it




A callback is a function that is to be executed after another function has finished executing. Hence we call it ‘call back’. In JavaScript, functions are objects. And those functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.

Let us take an example for a callback function:

In the above example, The function A will execute first. And after the execution of Function A, you will get a console log saying “This is console log 1” and after the execution of the function A, the second console log will be called. Hence, the final output will be:


This is console log 1
This is console log 2

Why Do We need a Callback Function?

JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events. Lets look at a basic example:

In the above example, we assume that the output of the above code would be something like:

This is function one
This is function two

But that is not always correct. Let us imagine a scenario, in which the first function (in our case, function One) contains some codes that are unable to execute immediately. In that case, we can not guarantee the same output, every time we execute the code. To make it easy to understand, let us recreate the above code, that takes a few seconds to execute by adding a setTimeout to it.

In the above example, we have delayed the execution of the codes inside function One by one second, by adding setTimeout function to it. Which means, the execution of the console.log inside it will be delayed by one second, where as the console.log inside function Two will be called immediately. The output will be:


This is function two
This is function one

Quite a big issue right? Well, we can solve this issue by using the callback function mechanism. Let us see how it works.

Recreating the Above Codes using Callbacks

Now, we can write the same code using callback mechanism to sort out our issues. The recreated code should look something similar to this:

Now, in the above example, the function One will start executing first. It will wait for one second for the first console statement is printed and after that function Two will be executed. Making the output something similar to this:


This is function one
This is function two


Please enter your comment!
Please enter your name here

Subscribe to our newsletter

Snehasish Nayak
I am Snehasish Nayak, a Senior Programmer at NIC, Bhubaneswar and a Google Product Expert.

Recent posts

Recent comments