JavaScript Callbacks

In Javascript, a callback function is a function that is passed into another function as an argument. This allows you to invoke that function with a return value. Remember, Javascript’s implementation within a browser is single threaded (well..until recently at least). That means that all of your code is executed within one linear operation. However, there are some functions in Javascript which are asynchronous. That means that they have the privilege to be invoked anywhere in that line of execution. Javascript callbacks are useful because they allow you to efficiently program for async functions.

Here’s a simple example. Suppose I have a program that is supposed to print out the letters “A, B and C”:

console.log('A' );

Okay, that’s not hard. Now, let’s expand this a bit. Suppose this program is split into two different functions. The first function prints A then calls another function which prints function B. Afterwards, it prints function C. Again, this wouldn’t be a hard program to write with those specifications.

However, pretend that we want to wait three seconds before function B is called. Why wait three seconds? Well, you might have a function that makes a request to a server and it takes time to get a response. So let’s pretend those three seconds represent some network activity happening. So here’s what the code would look like:

So the above code will print out: A, C then B. And that’s not the order that we want. So essentially, there are two ways that we could fix this. The most obvious way would be to move the console.log(‘C’) right after the doAfterDelay() function. This works because the settimeout function takes an anonymous function that is used as the callback. So this whole time, you were using callbacks and you probably didn’t even realize it.

The second way is to write our own callback. That is what we are going to do. Remember, a callback is just a function that is passed as a parameter. So in my doAfterDelay() function I setup a new argument called callbackFunction. Then I return the console.log(‘B’) in that argument. When I call doAfterDelay() in my settimout function, I pass in an anonymous function to it (using the new ES6 arrow functions). I could have also passed in a named function that I defined somewhere in the file. Finally, in this anonymous function I handle the callback (called in my return callbackFunction() ) and print out console.log (‘C’)’ Below is the final code:

The true power of callbacks really shine when you are dealing with multiple network request and you have a chain of execution happening. That will be covered in a later tutorial. You can view this final code on GitHub. In the next tutorial, we’ll take a look at how to deal with promises.