Callback — Ring ring, hello?

Muhammad A Khalid
2 min readFeb 13, 2021

In most cases, when writing code, it is executed in a sequential order. As in the example below, first x is created and assigned a value of 1, then y is created and assigned a value of 2, then finally sum is created and assigned a value of x + y. Nice. Simple. Clean. However, the code below is pretty simple. Some basic assignment and arithmetic. These actions don’t take a whole lot of time either so they are completed almost instantaneously. What happens when things start to get more complicated? What happens when the code hasn’t finished running and the next line is being called or you need to wait for the previous bit of code to finish before going onto the next step? Say hello to Callbacks.

Each bit of code happens one after the other

When we introduce more complex code, we can run into the issue of asynchronous programming. What is asynchronous programming? Asynchronous programming is when code is called before the previous code has finished running. This is very common when working with functions and APIs or even calls to databases.

Callbacks are the solution but they can be a little complicated. At its core a callback function is simply a parameter to another function. Beyond that, both functions and callbacks, are practically the same. Callbacks have their own set of code, they can be called in the same ways that a normal function and they can even have their own callback functions but that’s going into the territory of Callback Hell, and we try not to go there.

This is the most basic example of a callback function. We have two functions processUserInput which is a normal function and greeting which is the callback function because it is being passed into processUserInput as a parameter. processUserInput prompts the user for their name and then passes the name variable to greeting and alerts the message. Without a callback it is likely that the alert would happen before the user had time to respond to the prompt.

I hope you found this introduction to callbacks informative and remember to stay away from Callback Hell.

In the famous words of Elliot Witt, “The [callback] isn’t really complex but it can be a little complicated”

--

--