top of page
Writer's pictureThe Tech Platform

JavaScript Callback Function



In Javascript, Functions are objects. We can pass the objects to functions as parameters. And, also we can pass functions as parameters to other functions and we can call them inside the outer function. This is the situation where we call this process as callback function.

function print(callback) 
{
    callback();
}

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.


Below are some of the advantages for using Callback Function:

  1. Callback make sure that function is not going to run before a task is completed, it will run when the task is completed.

  2. It helps us to develop asynchronous javascript code and keep safe from error and problems.


Code:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Callbacks</h2>

<p>Adding two given numbers : </p>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(8, 5, myDisplayer);
</script>

</body>
</html>

Source: W3School


Output:




The Tech Platform






0 comments

Recent Posts

See All

Comentários


bottom of page