DEV Community

Audrea Cook
Audrea Cook

Posted on • Originally published at audthecodewitch.github.io on

Callback Functions with the Code Witch

The code witch, now well-versed in JavaScript closures, turned to a blank page in her spellbook. As she pondered the topic for her next entry, the little code witch recalled her technical interview.

“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:

Callback Functions

Callback functions occur frequently in JavaScript. In fact, their presence can be so common that they are easily overlooked. However, callbacks are a powerful bit of code magic, and they are not to be taken lightly.

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.

Hermoine Granger Brewing a Potion

To Name, or Not to Name?

You can use both named and anonymous functions as callbacks. First, we’ll start with the named function:

See the Pen Named Callback Function by Audrea Cook (@audthecodewitch) on CodePen.

This time, let’s pass an anonymous function as the callback:

See the Pen Anonymous Callback Functions by Audrea Cook (@audthecodewitch) on CodePen.

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:

See the Pen Asynchronous Callbacks by Audrea Cook (@audthecodewitch) on CodePen.

Danger!

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.

Ron Weasley Grimacing

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.

Helpful Resources

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:

  1. MDN - Of course I’m sending you to the docs.
  2. JavaScript is Sexy - I mean, they’re right. And they also have a pretty detailed description of callbacks.
  3. Callback Hell - Here’s a deeper look at the dangers of too many callbacks.

Top comments (0)