A function is a block of code that performs a particular task. For instance, printName() is a function that has a name argument and returns a name to the user.
I. Callback function
For instance, printName() is a function that takes another function myAge as an argument, and then printName() calls the myAge() function inside it.
Now we understood the defination of Callback but why do we need them? Let’s understand this with an example.
II. Why do we need a Callback function?
So in such situation, the Callback functions comes to the rescue. They ensure that the second function will not execute before the execution result of the first function. But the second function will execute right after the first one finishes its task.
For instance, In this, we are using the setTimeout() function (execute the block of code after a specified time) to delay the output of the first function.
In this, the printName() function is called after 5000 milliseconds, i.e., 5 seconds delay. Because of this delay, the output of the second function is executed before the output of the first function.
In the above example, the second function does not wait for the first function and executes first. However, if we want the second function to execute after the first function, we should use the Callback function. So now, let’s see the program with a Callback.
In the above example, the statements are executed in sequential order.
III. When we need them
A Callback function is specially used when we have to wait for a result that takes time. For example, we need to fetch data from a specific API, and after that, we need to use API fetched data in the second function. So in such cases, we will use Callback to perform the operations in their specific order.