JavaScript Callbacks



In JavaScript, since functions are objects we can pass them as parameters to another function. These functions can then be called inside another function and the passed function is referred to as a callback function.

Why Use Callbacks?

The following are the advantages of using JavaScript Callbacks ?

  • Encapsulation: Separates logic for better modularity.
  • Reusability: Allows different callback functions for different processing needs.
  • Asynchronous Execution: Commonly used in event handling, API requests, and file operations.

Using a Callback Function

Below is an example where an add() function performs addition and then calls multiplyResultByTwo(), which doubles the result and updates the webpage.

Following are the steps to perform the callbacks function in Java ?

  • add(a, b, callback) performs addition and calls callback(result).
  • multiplyResultByTwo(res) is the callback function that takes the result and doubles it.
  • When the button is clicked, add(4, 5, multiplyResultByTwo) is executed:
    • 4 + 5 = 9
    • multiplyResultByTwo(9) ? 9 * 2 = 18
    • The result (18) is displayed in the

The function that performs addition and calls a callback function ?

function add(a, b, callback) {
      callback(a + b);
   }

Callback function that multiplies the result by 2 and updates the webpage using the document.querySelector() ?

function multiplyResultByTwo(res) {
      document.querySelector(".sample").innerHTML = res * 2;
   }

addeventlistener to trigger the add function with a callback ?

document.querySelector(".btn").addEventListener("click", () => {
      add(4, 5, multiplyResultByTwo);
   });

Example

Below is an example of a Javascript Callbacks ?

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>JavaScript Boolean constructor Property</h1>
<p class="sample"></p>
<button class="btn">CLICK HERE</button>
<h3>
Click on the above button to call the add function which calls back
another function
</h3>
<script>
   function add(a, b, callback) {
      callback(a + b);
   }
   function multiplyResultByTwo(res) {
      document.querySelector(".sample").innerHTML = res * 2;
   }
   document.querySelector(".btn").addEventListener("click", () => {
      add(4, 5, multiplyResultByTwo);
   });
</script>
</body>
</html>

Output

On clicking the "CLICK HERE" button ?

Conclusion

Callbacks are a fundamental concept in JavaScript that allows functions to execute dynamically based on specific conditions. They enhance code modularity, reusability, and flexibility, making them essential for handling asynchronous operations like event listeners and API calls.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-02-26T19:37:22+05:30

618 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements