JavascriptNode.JSProgrammingTechnology

Beginners Guide to the Callback Function in Javascript

If you want to excel in Javascript programming it’s essential that you get a good hang of callback functions. What it does, why is it used and why does it even behave the way it does?

Frankly speaking, I used to find the callback functions a bit confusing. This even exacerbated when I started learning Nodejs as more or less every package in the server-side version of Javascript invokes callback functions in order to achieve something.

So I decided that since there’s no refuge other than getting myself acquaint with these functions, I should better understand how they work.

So the purpose of this article is to help those who, like me, are also left bewildered and clueless when they read javascript codes which rely on callback functions. I hope this article will serve as a great learning resource and to set a firm grasp on this concept.


Also Read: Beginner’s Guide to Javascript Recursion


What is a Callback Function?

In simple terms, a function within a function is called a callback function.

If we use the liberty of adding a bit more complexity then the definition of a function that executes only after a particular function is executed is called a Javascript function.

The callback function is introduced within a function as a parameter. The function which has a callback function within itself is called a higher-order function.

A callback function can be defined both within and outside of the higher-order function.

function higherOrderFunction([optionalparameter1], callbackFunction) {
        doSomething;
        callbackFunction();
}


Why do we even need a callback function?

Since Javascript is an event-driven programming language (BTW, it’s also a procedural, structural, object-oriented language as well) and all the kinds of events keep taking place in a browser (such as a mouse click etc.) the javascript is never short of reasons to keep on executing the code.

Therefore, instead of waiting for a response on some preceding piece of code first and then moving on to the later it jumps to the next line of code, execute it and then display the output (or performs an action) of the first one as soon as it receives the response.

Given this behavior, sometimes we want to make sure that certain code does not run until a particular piece of code executes. In that case we need to introduce a callback function.

Since a callback function is just like an ordinary javascript function, and the mere use of it makes it a “callback”, it is rightfully said that a callback function is not what they are but how they’re used.

To understand better, let’s have a look at this simple example:

function firstFunction(){
        console.log('This program should run first');
}

function secondFunction(){
        console.log('This program should run second');
}

firstFunction();
secondFunction();

Open up developers tool right in the browser in which you’re reading this article. CTRL+Shift+i for Google Chrome, F12 in Internet Explorer in Windows and paste the above code in the console and hit enter.

Google Chrome Developers Tools Ctrl+Shift+i
Google Chrome – Developer Tools (Ctrl + Shift + i)

The output would be:

//This program should run first
//This program should run second

That’s quite obvious and normal. This is how the output should be. Right?

Now, let’s assume that the first function <code>firstFunction()</code> gets “caught up” due to some reasons. What this means is that either the code requires some time to display the output or needs some condition to be true (or false) before it gets executed.

In that case what would be the output then?

Well, let’s write the above code again but this time, let’s delay the first function by half a second.

function firstFunction(){
    setTimeout(function(){
        console.log("This program should run first");
      }, 500 );
}

function secondFunction(){
        console.log('This program should run second');
}

firstFunction();
secondFunction();

This time, the second function will display first. Here’s the output:

//This program should run second
//This program should run first

Did you see that?

Despite writing the firstFunction() first, the output of secondFunction() is displayed first. It’s not like that the Javascript skipped the delaying function. It did read the code in the series that we wrote but instead of waiting for half a second for the response, it jumped to the next line, executed it and then executed the first function when it actually received the response.

Due to this very same reason that javascript does not wait for the response, we need to introduce callbacks in our code. So that to make sure that Javascript does not execute the later portion of the code before receiving the response from the first.

This is important in many cases. For e.g., in NodeJs, we want the code not to display any further information unless it receives a response from the server.


Also Read: GET & POST Methods in Node.js and Express.js



…Let’s Create a Simple Callback now.

In javascript, you can create a simple function like this:

function simpleFunction() {
    console.log('Say Hi');
};
simpleFunction();
//Output: Say Hi

The same can be achieved with the help of a parameter within a function.

function simpleFunction(x) {
    console.log(x);
};
simpleFunction('Say Hi');

//Output: Say Hi

Being a higher-order object, javascript functions can also be stored in a variable or the function can be used instead of a parameter within a function.

Here’s an example:

function simpleFunction(x) {
    console.log(x);
};

function greetings(){
  console.log('Say Hi');
};

simpleFunction(greetings());

//Output: Say Hi

The greetings() function inside the simpleFunction() is the callback function and this is what it needs to create one. Simple

Now, let’s continue the above example where we delayed our first function for half a second, let’s add a callback function in our code so as to make sure that the second function does not execute before the first despite there being a delay.

function firstFunction(callback) {
    setTimeout(function(){
            console.log("This program should run first");
            callback();
          }, 500 );
};

function secondFunction() {
    console.log('This program should run second');
};

firstFunction(secondFunction);

Run the above code in the console and this will be the output:

//Output: This program should run first
//Output: This program should run second

What you will notice is that for 500 milliseconds, the program will not generate any output. It will wait for the first response and then will move on to execute the next piece of code which in our case is the secondFunction()

Reason?

Because we made our secondFunction() a callback function and recalling the definition of the callback function which is introduced to make sure that it only runs after a certain step, the secondFunction() does not execute before firstFunction() even though it experiences a delay of 500 milliseconds.

That’s it…!

Since this article was to serve as a guide for the beginners, I’d conclude it at this point. You can add further complexities as well. Say, by adding some parameters in the callback function and see how it behaves.

However, having said that, I hope that you’ve taken the golden nuggets from the article and now you can implement the callback functions in javascript with ease as you may now know what they are, what purpose do they serve and how you can create and invoke callback functions in your program to manipulate the order of your code execution.

Additionally, if you want to learn more about the Callback Functions, let me redirect you to a great article to clear further nuances. I hope this will help.

Feel free to ask any related questions down below in the comments section. I’ll try to respond to them in the most readily manner.