What are callbacks in JavaScript?
Passing function as an argument
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.
Example
Have a look at the code given below.
This is how it’s working:
-
Lines 1-9: The
calculateSumfunction receives a numbern, and acallbackfunction. It sums the numbers from 1 up ton, prints out the calculatedsumand passes it to the callback function, as shown on Line 8. -
Lines 12-14: When calling the
calculateSumfunction, the callback function has also been defined inside the function call. It takes thesumpassed to it bycalculateSumand 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