Sitemap
Steven Hancock

Steven Hancock

JavaScript instructor and developer.

The Essential JavaScript Callback

4 min readDec 22, 2022

--

Press enter or click to view image in full size
Calling Back. We do it in JavaScript all the time. Photo by freestocks on Unsplash

Without callbacks it would be very difficult to do anything interesting with JavaScript. Callbacks have been with the language ever since the beginning, but the application of callbacks has increased more and more. In fact many new patterns added to the language in recent years makes using callbacks possible in more interesting ways.

But I’m getting ahead of myself. Let’s first define callbacks with some examples and then we will look at the two main ways callbacks are used within JavaScript.

Defining Callbacks with Examples

Simply put, a callback is a function that is passed into another function as an argument and then at some future point, that function is invoked to complete an additional task. The name ‘callback’ comes from the fact that the code calls back to the function that was passed in.

The nature of functions in JavaScript make it possible for callbacks to occur. The fact that they are first class and can be higher order makes this possible. I dive into both concepts in another article.

Because of the nature of functions, we have a number of built in methods that make use of callbacks. These are a good way to introduce them. For example, lets take a look at the map method available on arrays.

The map method iterates over every element in an array and applies a callback function to each element. The end results is a new array. In the example just provided, we pass in a callback function that simply doubles the number in the array. In this example, the callback function is called back 6 times; once for each element in the original array.

A common callback pattern we see when working with HTML pages is the creation of an event listeners. The addEventListener method is the preferred pattern for adding listeners to a DOM object. It requires a callback function.

After creating this listener, it will respond to any key press by invoking the callback function. Then the string equivalent for the key that is pressed is displayed to the console.

We can also create our own functions that make use of callbacks. Many times this can make a function more flexible.

In this example we have a function updateObjs that will take any object and then update the values of that object using a function that is passed in. We first call it to update all the numbers to actual numbers instead of strings. Then we call it to update all strings by capitalizing the first letter.

The updateObjs function becomes more flexible, and we only need to write the code that iterates through an object once. This shows some of the advantages of writing code that makes use of callbacks.

Synchronous Callbacks

Callback functions can be used in synchronous or asynchronous patterns.

Get Steven Hancock’s stories in your inbox

Join Medium for free to get updates from this writer.

The previous example is a synchronous pattern. The code runs from start to finish, sequentially, and blocks additional code from running until it completes. This sequential nature includes the callback invocation. The callback becomes part of the sequentially running code and must complete before additional code can run.

But callbacks are also essential to asynchronous code in JavaScript and makes up some of the interesting things we can do with JavaScript.

Asynchronous Callbacks

Probably the most commonly referred to asynchronous piece of code that uses a callback is setTimeout.

The setTimeout function allows us to call another function after a certain amount of time. The timer is handled by the outer environment, the browser, so it doesn’t block additional code from running. Once the time has expired, the callback is placed in the message queue and then is added to the call stack for execution when space is available.

Based on the console output, the second console.log statement runs before the callback function even though the time is set to 0 milliseconds. So no code blocking occurs in this asynchronous example. Yet without a callback we could not accomplish this.

Press enter or click to view image in full size
Console output

Another asynchronous pattern that makes use of callbacks is a promise. Promises are generally used when we are awaiting the completion of some asynchronous operation.

As an example, the Fetch API lets us retrieve data from sites. However, we don’t need to wait until the code completes. Other code can run while we are waiting for the site to return the data.

Fetch returns a promise once it completes, we must handle the returned data with a .then method. But in order for the .then method to work we need to pass in a callback function. The callback is essential. So the first callback we use in the example above converts the response to a JSON object. This then returns another promise. The second callback logs the ‘todo’ item to the console.

As we can see the code is asynchronous because the console.log statement displays first on the console.

Press enter or click to view image in full size
Console output

Conclusion

Callbacks are central to many things we do in JavaScript. Without them we could not accomplish any asynchronous coding. They also allow us to do some interesting things with our synchronous code. Basically callbacks are essential to JavaScript.

Follow along for many more articles on JavaScript.

Comment below to add your own thoughts about the essential nature of callbacks.

--

--

Steven Hancock
Steven Hancock

JavaScript instructor and developer.