Callback Functions In JavaScript

Callback functions

 
This article will revolve around the below questions:
  1. What is a callback function?
  2. Syntax of the callback function
  3. When to use a callback function?
  4. Best practices

What is a Callback function?

 
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. Implementing callback is also called the callback pattern.
 
Syntax
  1. function outerFunction(callbackFunction) {  
  2.      //Some code here  
  3.      callbackFunction();  
  4. }  
  5. function callbackFunction(){  
  6.      //some code here  
  7. }  

When to use a callback function?

 
1. Synchronous callback functions
 
These functions are used to make the code more versatile.
 
For example, you can perform different operations on data after getting the input from the user.
  1. function getNumbersFromUser(callbackFunction){  
  2.      //some code here  
  3.      //Numbers a,b received from a user  
  4.      var a = 4, b = 5;  
  5.      callbackFunction(a,b);  
  6. }  
  7. function multiplication(a,b){  
  8.      document.write("Multiplication is : "+a*b);  
  9. }  
  10. //Can perform multiple operations on the same number set.  
  11. getNumbersFromUser(multiplication);  
  12. //OR  
  13. function addition(a,b){  
  14.      document.write("Addition is : "+(a+b));  
  15. }  
  16. //Can perform addition operations on the same number set by just changing callback function.  
  17. getNumbersFromUser(addition);   
The above series of operations can be performed without a callback function in the following ways.
  1. //Call function within another function  
  2. function getNumbersFromUser(){  
  3.      //some code here  
  4.      //Numbers a,b received from a user  
  5.      var a = 4, b = 5;  
  6.      multiplication(a,b);  
  7. }  
  8. function multiplication(a,b){  
  9.      document.write("Multiplication is : "+a*b);  
  10. }  
  11. getNumbersFromUser();  
  12.    
  13. //------------OR-----------------  
  14.    
  15. function getNumbersFromUser(){  
  16.      //some code here  
  17.      //Numbers a,b received from a user  
  18.      var a = 4, b = 5;  
  19.      addition(a,b);  
  20. }  
  21. function addition(a,b){  
  22.      document.write("Addition is : "+(a+b));  
  23. }  
  24. getNumbersFromUser();   
In the above code snippet, either multiplication or addition operation is mandatory to perform. However, extending the functionality is difficult.
  1. //Call function after another function  
  2. function getNumbersFromUser(){  
  3.     //some code here  
  4.     //Numbers a,b received from a user  
  5.     var a = 4, b = 5;  
  6. }  
  7. function multiplication(a,b){  
  8.      document.write("Multiplication is : "+a*b);  
  9. }  
  10. function addition(a,b){  
  11.      document.write("Addition is : "+(a+b));  
  12. }  
  13. //Can perform multiple operations on the same number set.  
  14. getNumbersFromUser();  
  15. multiplication(a,b);  
  16. //------------OR-----------------  
  17. addition(a,b);  
 
In the above code snippet, extending the functionality is easy. However, it is dependent on the developer's choice to perform actions. In the above example, if the developer doesn’t call multiplication/addition function, there will not be any output of code.
 
Moral - If you want to enforce a certain set of activities with versatile code, use callback functions.
 
2. Asynchronous callback functions
 
If you want to operate on data fetched asynchronously/execute a function after a certain time, a callback is your friend. JavaScript uses a callback in the following scenarios.
  1. AJAX call: CRUD operations on data from the server
  2. CRUD operations on data from the file
  3. Event listeners
  4. Timeout methods : setTimeout, setInterval
Below is a simple demonstration of how callback is used in AJAX call.
  1. $.ajax({  
  2. url: "valid_API_endpoint",  
  3. success: operationAfterSuccess  
  4. });  
  5. //This will execute if data fetched successfully from given URL  
  6. function operationAfterSuccess(result)  
  7. {  
  8.      //some code here  
  9. }  

Best Practices

 
1. Make sure the callback is a function before execution.
  1. function outerFunction(callbackFunction) {  
  2.     //Some code here  
  3.     if(typeof callbackFunction === "function")  
  4.          callbackFunction();  
  5. }  
  6. function callbackFunction(){  
  7.     //some code here  
  8. }
2. Chaining anonymous callback functions one after another leads to callback hell. So, always use named functions instead of an anonymous one.