Just like almost everything in JavaScript (except primitive data types), functions are an object type. So like any other object types, functions can be passed to other functions.
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.
Since JavaScript is an event-driven language, you can’t just call one function after another and hope both of the functions will execute in the right order.
Instead of waiting for a response, JavaScript keeps on executing, while listening for events in the background. This is where callbacks prove to be really beneficial since they can be called from inside the called function when the time is right e.g. to return some kind of useful data.
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.
Free Resources