javaScript Callback

--A callback function is a function passed into another function as an argument. Don't relate the callback with the keyword, as the callback is just a name of an argument that is passed to a function.

--The callback function runs after the completion of the outer function. The callback function executes after the completion of the outer function.



Why do we need Callback Functions?


--JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.


--Callbacks are primarily used to handle the asynchronous operations -making an API request to Google Maps,the registering event listeners, fetching or inserting some data into/from the file, and many more.


-- It is useful to develop asynchronous JavaScript code and keeps us safe from problems and errors.

--In JavaScript, the way to create a callback function is to pass it as a parameter to another function as a parameter to another function and call it right after the completion of the task. Let’s see how…



How  can we create Callback Functions?


Example 1:-

<html>  
<head>  
<style>  
</style>  
</head>  
<body>  
/ Addition() function is called with arguments a, b
// and callback, callback will be executed just 
// after ending of add() function
function Addition (a, b, callback)
{
    document.write("the sum of ${a} and ${b} :${a+b} "+</br> );
    callback();
}
 // Display() function is called just
   // after the ending of add() function 
function Display()
{
    document.write("this will print after the execution of Addition function." );
}
Addition(5,8,Display);
</script>  
</body>  
</html>  
Output:-

the sum of 5 and 8: 13
this will print after the execution of Addition function.


** Callback Functions create using anonymous functions:- 


<html>  
<head>  
<style>  
</style>  
</head>  
<body>  
/ Addition() function is called with arguments a, b
// and callback, callback will be executed just 
// after ending of add() function
function Addition (a, b, callback)
{
    document.write("the sum of ${a} and ${b} :${a+b} "+</br> );
    callback();
}
 // add function is called with arguments given below.
  

Addition(5,8,function Display()
{
    document.write("this will print after the execution of Addition function." );
});
</script>  
</body>  
</html>  

Output:-

the sum of 5 and 8: 13
this will print after the execution of Addition function.

Post a Comment

1 Comments