...see more

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

Example

Using a callback, you could call the calculator function (myCalculator) with a callback (myCallback), and let the calculator function run the callback after the calculation is finished:

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

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

myCalculator(5, 5, myDisplayer);

In the example above, myDisplayer is a called a callback function.

It is passed to myCalculator() as an argument.

Note

When you pass a function as an argument, remember not to use parenthesis.

Right: myCalculator(5, 5, myDisplayer);

Wrong: myCalculator(5, 5, myDisplayer());

Comments

Leave a Comment

All fields are required. Your email address will not be published.