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.

 function myfunction(x, a)
    let s=a(x);
    document.write('Hello '+s);

function getName(str)
    return str;

myfunction('Kavita', getName);


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.

    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);

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.

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

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 handler, click here.

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

Understanding JSON Web Tokens

Understanding HTTP Requests and Responses

What is Asynchronous JavaScript?

JavaScript Code for Event Handling

Callback Functions in JavaScript

Arrow Functions in JavaScript

JavaScript Code Examples

Show or Hide TextBox when Selection Changed in JavaScript

Changing Style of HTML Elements using getElementsByClassName() Method

Creating Classes in JavaScript


You may also like...