“Of all the topics we discussed, which one was the most embarrassingly obvious?” she mused. “Which one nearly drove me to cast an Unforgivable Curse on myself when I finally matched the term to the code concept?”
She thought for a moment longer and, with a grim smile, began to write:
Put simply, a callback is a function that is passed as an argument inside another function. The callback is then invoked within that parent function.
Magic Using Callbacks
Callback functions are relatively simple to define, but a few quick examples will reveal their true power.
To Name, or Not to Name?
You can use both named and anonymous functions as callbacks. First, we’ll start with the named function:
This time, let’s pass an anonymous function as the callback:
Sync, or Async?
Callbacks can be used in both synchronous and asynchronous code. In both examples above, the callbacks are synchronous, that is, they are executed immediately. Asynchronous callbacks are useful when one wishes to control when specific code is executed, like in event handlers and fetch requests. Let’s look at an example:
Callbacks are pretty straightforward, but beware of “Callback Hell,” also known as the “Pyramid of Doom.” Callback functions can also take arguments, including other callback functions. This can lead to deeply nested functions that are inefficient and often difficult to debug.
You can avoid this trap by naming your callback functions instead of using anonymous ones. Another workaround is to use promises, which are beyond the scope of today’s post but are explained in depth here.
I found these articles to be particularly helpful in my research. If you are looking for some more information about callbacks, give them a look: