Snipps by Patrik

JS Callbacks

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.


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;

myCalculator(5, 5, myDisplayer);

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

It is passed to myCalculator() as an argument.


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

Right: myCalculator(5, 5, myDisplayer);

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


Leave a Comment

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