JavaScript Callbacks


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

Following is the code for JavaScript Callbacks −

Example

 Live Demo

<!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 −

Updated on: 07-May-2020

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements