Call Back Functions in Javascript

A callback is a function that is passed to another function as a parameter and can be called from within that function.

For example, say we have a function that processes the data returned from an API endpoint, and another function that actually gets the data.

Function to Process the Retrieved Data

The function that gets the data can do so using ajax, for example. It can accept the function that processes that data as a parameter and call it whenever the data is ready.

Function Accepting Another Function (Callback Function

The function that is passed to the other function is called a callback function.

This is very useful mechanism in asynchronous programming to inform other functions when a certain process is complete. The caller is in effect saying, 'Yo, that data you wanted, here it is.'

I run the above code in my web browser console and got the following message popping up after 3 seconds:

Callback output Example
Callback output Example

Personally, I find callbacks a very useful mechanisms for creating intuitive interfaces that notify the user whenever some long running process completes, so that they can proceed to do something else. For example, when a user clicks a button, I can put up a modal that blocks out the interfaces so that the user has no option but to wait, and then, when the action being processed in the background completes, the modal vanishes and a message pops up saying 'Your Request has been processed.'

Of course, there are processes which need to be run quietly in the background. However, for most actions, the user often has to wait to know whether their request was successful or not before they can proceed to the next action. This is because their next action will be determined by the results of their current request. Callbacks come in quite handy here!

Of course, there is a better way of doing this. Promises are a new and clean way of doing exactly this. But that is a topic for another day!

Any questions?