Introduction

Callback functions are a concept that should be explained because you’ll see them constantly in JavaScript. Functions are objects so we can pass them as parameters; this important key makes callback functions viable. Today, we explain what are and how to make callback functions.

What Are CallBacks?

Callbacks are functions used by another function that will be executed later.  They’re definitely not magical, but they can appear so. Now, you might ask why would I need this? They are crucial when dealing with asynchronous code.

Asynchronous code is code that is run in the background while your program executes. The program continues execution, and then the asynchronous code task completes when it’s done. A good example of where this is useful is reading large files. If you read a large file, synchronously (waiting until the file is read), you may wait minutes before the process is complete. For the user that could be jarring and should not be the go-to way of reading larger files or handling time-consuming tasks. Asynchronous code and callbacks remedy this issue by running our function when it’s ready. So, how do we create a callback?

Creating A Callback

To create our own callback function is easy; you write them like a normal function. Now, the important part is understanding the parameters the callback will take in the future. The function that takes the callback, you can call this the caller, has to provide the right information to that callback function for executing a task. Here are some examples to illustrate callback functions. Each one uses the same caller function.

Here’s example output in the console:

The examples do similar things, they both take the function and pass the first parameter in the caller to the callback. You can even write an anonymous function as you can see in example 3 and 4 because they’re only being created not executed. Now, this may be confusing, but you could think of callbacks as piping the output from one function to another function once processing is complete. Note, any function can be used as a callback for the caller, except a bound function (these functions have their parameters set already). These trivial examples are similar to chaining, but the difference is chaining will immediately execute the next function whereas callbacks wait until processing is complete because they’re a part of the function’s execution.

And that’s how you make a callback function. I hope this explanation helps you and improves your code.

%d bloggers like this: