Tutorialspoint.dev

JavaScript | Callbacks

Callbacks are a great way to handle something after something else has been completed. By something here we mean a function execution. If we want to execute a function right after the return of some other function, then callbacks can be used.

JavaScript functions have the type of Objects. So, much like any other objects (String, Arrays etc.), They can be passed as an argument to any other function while calling.

JavaScript code to show the working of callback:

Code #1:

<script>
  
   // add() function is called with arguments a, b
   // and callback, callback will be executed just 
   // after ending of add() function
   function add(a, b , callback){
   document.write(`The sum of ${a} and ${b} is ${a+b}.` +"<br>");
   callback();
   }
     
   // disp() function is called just
   // after the ending of add() function 
   function disp(){
   document.write('This must be printed after addition');
   }
     
   // Calling add() function
   add(5,6,disp);    
     
</script>

Output:

The sum of 5 and 6 is 11.
This must be printed after addition

Explanation:
Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers.

As a result, the add() is invoked with 1, 2 and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the addition output.



Code #2:
An alternate way to implement above code is shown below with anonymous functions being passed.

<script>
  
   // add() function is called with arguments a, b
   // and callback, callback will be executed just 
   // after ending of add() function
   function add(a, b , callback){
   document.write(`The sum of ${a} and ${b} is ${a+b}.` +"<br>");
   callback();
   }
   
   // add() function is called with arguments given below
   add(5,6,function disp(){
   document.write('This must be printed after addition.');
   });
     
</script>

Output:

The sum of 5 and 6 is 11.
This must be printed after addition.

Callbacks are primarily used while handling asynchronous operations like – making an API request to the Google Maps, fetching/writing some data from/into a file, registering event listeners and related stuff. All the operations mentioned uses callbacks. This way once the data/error from the asynchronous operation is returned, the callbacks are used to do something with that inside our code.



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter