When a function is passed as an argument, it is called a callback function. This callback function can be invoked inside the function calling it at any point, especially when some routine or action has been completed.
Have a look at the code given below.
This is how it’s working:
Lines 1-9: The
calculateSum function receives a number
n, and a
callback function. It sums the numbers from 1 up to
n, prints out the calculated
sum and passes it to the callback function, as shown on Line 8.
Lines 12-14: When calling the
calculateSum function, the callback function has also been defined inside the function call. It takes the
sum passed to it by
calculateSum and uses that sum to print out the average.
The callback function can also be defined separately and then passed to the function call.