JavaScript

Callback Functions in JavaScript

Basically, Callback Functions in JavaScript provide us a way to pass a function as a parameter to another function.

In fact, callback functions are very useful in performing asynchronous operations and registering an event listener.

Examples of Callback Functions in JavaScript

As an illustration, the following is an example of a simple callback function that just returns a string.

<script>
 function myfunction(x, a)
 {
    let s=a(x);
    document.write('Hello '+s);
 }

function getName(str)
{
    return str;
}

myfunction('Kavita', getName);

</script>

In order to view the complete code click here.

Another example of using callback functions is given below. As shown below, here different functions serve as the callback functions in each function call.

 <script>
    function add(a, b)
    {
       return a+b;
    }
    function subtract(a, b)
    {
      return a-b;
    }
    function multiply(a, b)
    {
      return a*b;
    }
    function divide(a, b)
    {
      return a/b;
    }

    function ArithmeticOperations(x, y, f)
    {
	let z=f(x, y);
        document.write("Result = "+z+"<br/>");
    }

    ArithmeticOperations(12, 78, add);
    ArithmeticOperations(12, 78, subtract);
    ArithmeticOperations(12, 78, multiply);
    ArithmeticOperations(879, 78, divide);
  </script>

In order to view the complete code click here.

As an illustration of using callback functions in an asynchronous function call, a callback function can be used as a parameter to setTimeout() function. The following example shows that how the callback function displays the alert message after a timeout of 5 seconds.

<html>
<head>
 <title>Asynchronous Function</title>
 <script>
 setTimeout(showMessage, 5000);
 function showMessage()
 {
    alert("Register for our News Letter!");
 } </script>
<body>
  <center><h1>Welcome to Our Website!</h1></center>
</body>
</html>

Apart from being used in asynchronous function calla, the callback functions are also used in registering event handlers dynamically. For more information on registering event handlers, click here.


Related Topics

Evolution of JavaScript from ES1 to ES2020

Understanding Document Object Model (DOM) in JavaScript

Introduction to Programming in TypeScript

Creating Classes in TypeScript

Working with Arrays in TypeScript

Significance of Tuples in TypeScript

Explaining Interfaces in TypeScript with Examples

How to Create and Use Arrow Functions in TypeScript

Understanding JSON Web Tokens

Java Practice Exercise

Introduction to HTML DOM Methods in JavaScript

Changing Style of HTML Elements using getElementsByClassName() Method

Show or Hide TextBox when Selection Changed in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *