Advanced JavaScript: Callback Design Pattern and Callback Function

Introduction

 
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 its 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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>    
  2. <!DOCTYPE html>    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head runat="server">    
  5. </head>    
  6. <body>    
  7.     <form id="form1" runat="server">    
  8.         <script>    
  9.             function call() {    
  10.                 alert("I am callback function");    
  11.             }    
  12.             function a(callBack) {    
  13.                 callBack();    
  14.             }    
  15.             //Passing function name as argument    
  16.             a(call);               
  17.         </script>    
  18.     </form>    
  19. </body>    
  20. </html> 
In this example, we have defined two functions ("call" and "a") and then we are calling function by passing the name of the call() function. Then we are calling the callback function from function a. Here is a sample output.
 
Callback in JavaScript
 
We are seeing that the call function is being called after execution of the a() function. This is a 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 a 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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>    
  2. <!DOCTYPE html>    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head runat="server">    
  5. </head>    
  6. <body>    
  7.     <form id="form1" runat="server">    
  8.         <script>    
  9.             var abc = function () {    
  10.                 alert("Thsi is anonymous callback function");    
  11.             };    
  12.             function call(callback) {    
  13.                 callback();    
  14.             }    
  15.             call(abc);    
  16.         </script>    
  17.     </form>    
  18. </body>    
  19. </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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>    
  2. <!DOCTYPE html>    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head runat="server">    
  5. </head>    
  6. <body>    
  7.     <form id="form1" runat="server">    
  8.         <script>    
  9.             function message(str,callback) {    
  10.                 document.write(str);    
  11.                 callback();    
  12.             }    
  13.             message("This is message"function () {    
  14.                 alert("Message has displayed");    
  15.             });    
  16.         </script>    
  17.     </form>    
  18. </body>    
  19. </html> 
implement callback
 
This is another style of the callback function, we can say it's jQuery's style of a 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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>    
  2. <!DOCTYPE html>    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head runat="server">    
  5. </head>    
  6. <body>    
  7.     <form id="form1" runat="server">    
  8.         <script>    
  9.             function abc() {    
  10.                 alert("I am callback function. type checked");    
  11.             }    
  12.             function xyz(callback) {    
  13.                 if (typeof callback == "function")    
  14.                     callback();    
  15.                 else    
  16.                     alert("Argument is not function type");    
  17.             }    
  18.             xyz(abc);     
  19.         </script>    
  20.     </form>    
  21. </body>    
  22. </html> 
Here we are calling a function after checking it's typing. We are using the typeof operator to check it's typing.
 
Callback function before call
 
Pass argument to the callback function
 
In this example we will see how to pass an argument to the callback function. Try to understand the following example.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>    
  2. <!DOCTYPE html>    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head runat="server">    
  5. </head>    
  6. <body>    
  7.     <form id="form1" runat="server">    
  8.         <script>    
  9.             function abc(var1,var2) {    
  10.                 alert(var1 + var2);    
  11.             }    
  12.             function xyz(name,surname,callback) {    
  13.                 if (typeof callback == "function")    
  14.                     callback(name,surname);    
  15.                 else    
  16.                     alert("Argument is not function type");    
  17.             }    
  18.             xyz("Sourav "," Kayal", abc);     
  19.         </script>    
  20.     </form>    
  21. </body>    
  22. </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 a 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 a few more interesting concepts of JavaScript. Happy day.