Advanced JavaScript: Callback Design Pattern and Callback Function

Welcome to the "Advanced JavaScript" article series. In this series we are talking about the advanced concepts of the JavaScript programming language. We have already covered many more important topics. You can read them here:

This article explains callback functions in JavaScript. If you are an experienced JavaScript developer or have experience in jQuery, then most probably the concept is not new to you.  But sometimes what happens is that without knowing how it works, we use many things and it solves our problem. (Yes, it really does solve it, most of the time.) But it's not always the recommended method and for the long run it will not work. Ha..Ha.. So, if you are very new to this topic or have implemented a callback function without proper knowledge then this article is for you.

Go back to old days

To understand callback functions we need to understand the prior technology; from the era of functional programming.  Where everything was represented by functions, one function call to another to execute certain operations. And the most beautiful nature of a function call is that functions return a value.

And obviously this is very important in a parent-child thread environment. The caller function/thread should know the exit status of the called function. This way of program implementation is called the functional programming approach. Ok, so we have understood the concept of the functional programming approach. Fine, but what is the relation between JavaScript callbacks and the functional programming approach? There is a deep relation between them.

What is the callback approach?

The callback design approach is nothing but the implementation of a functional design approach. We know that there is no concrete class implementation in JavaScript and everything is an object and obviously a function is also one type of object in JavaScript. The specialty of a function type of object is "It is a first class object". In other words, it enjoys a higher priority in the application.

We can now pass a function as a parameter of another function. And when the function (called) function finishes it's execution it can call another function (which is nothing but a callback).  So, the function that will execute after the execution of some other function is called the callback function.  JavaScript and various JavaScript libraries (like jQuery) use callback functions every now and then.

Start with a sample example

We will now implement a few callback functions in this section. Try to understand the following code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
</
head>
<
body>
   
<form id="form1" runat="server">
       
<script>
           
function call() {
                alert(
"I am callback function");
            }

           
function a(callBack) {
                callBack();

            }

           
//Passing function name as argument
            a(call);
           
       
</script>
   
</form>
</
body>
</
html> 

In this example, we have defined two functions ("call" and "a") and then we are calling function a by passing the name of the call() function. Then we are calling the callback function from function a. Here is sample output.

Callback in JavaScript

We are seeing that the call function is being called after execution of the a() function. This is the very basic example of callback functions. In this example we have passed the function name. If needed we can pass the name of an anonymous function. Try to understand the following code.

Pass anonymous function to callback method

In this example we will assign an anonymous function to the callback method. At first we will create one anonymous method using the var keyword then we will pass this var as an argument.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
</
head>
<
body>
   
<form id="form1" runat="server">
       
<script>
           
var abc = function () {
                alert(
"Thsi is anonymous callback function");
            };

           
function call(callback) {
                callback();

            }

            call(abc);

       
</script>
   
</form>
</
body>
</
html> 

Here is a sample example. We are seeing that the callback operation is being performed as in the example above.

anonymous function to callback method

Another style to implement callback

This is another style to implement a callback function. In this case control will return to the caller function after the execution of the called function. Try to understand the following code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
</
head>
<
body>
   
<form id="form1" runat="server">
       
<script>
           
function message(str,callback) {
                document.write(str);

                callback();

            }

            message(
"This is message", function () {
                alert(
"Message has displayed");
            });

       
</script>
   
</form>
</
body>
</
html> 

implement callback

This is another style of callback function, we can say it's jQuery's style of callback function.

Check callback function before call

It's very good practice to check the callback argument before it is called. If the callback argument is not a function type then it will throw an error. Here is a sample example of a callback implementation.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
</
head>
<
body>
   
<form id="form1" runat="server">
       
<script>
           
function abc() {
                alert(
"I am callback function. type checked");
            }

           
function xyz(callback) {
               
if (typeof callback == "function")
                    callback();

               
else
                    alert(
"Argument is not function type");
            }

            xyz(abc);
 
       
</script>
   
</form>
</
body>
</
html>

Here we are calling a function after checking it's type. We are using the typeof operator to check it's type.

Callback function before call

Pass argument to callback function

In this example we will see how to pass an argument to the callback function. Try to understand the following example.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
</
head>
<
body>
   
<form id="form1" runat="server">
       
<script>
           
function abc(var1,var2) {
                alert(var1 + var2);

            }

           
function xyz(name,surname,callback) {
               
if (typeof callback == "function")
                    callback(name,surname);

               
else
                    alert(
"Argument is not function type");
            }

            xyz(
"Sourav "," Kayal", abc); 
       
</script>
   
</form>
</
body>
</
html>

In the "xyz()" function we are passing three arguments, the first two arguments are strings and the third argument is the callback function name. Here is sample output.

Pass argument to callback function

Conclusion

In this article we have learned the concept of callback functions.  I hope you have understood the concept. In a future coming series we will learn few more interesting concepts of JavaScript. Happy day.

Next Recommended Readings