Callback Functions are those functions which are passed as an arguments to another function. And the function in which these are passed is called Higher – Order Function.
Need Of Callback Function In JS
Actually when we run code asynchronously using setTimeOut() or await() function, then even before that block of code is run, the code beyond that starts executing. Due to which sometimes errors also come in the program or the code does not run according to logic.
In the example above, a function do_sum() is created to add 2 numbers. We assume that the do_sum() function will take some time to add up the numbers. But the code which takes time to execute inside the function is returning 0 value do_sum() even before its complete execution.
But by using the Callback Function, those errors can be avoided, because the function for which the callback function is passed as an argument, the callback functions run only after that function is completely executed.
To do the same example using the callback function, we will do something like this-
Much the same, in whichever function we pass the callback functions, we get as a parameter in that function, it is called wherever it is needed.