HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Callbacks

A callback is a function passed as an argument to another function. This technique allows a function to call another function only after its task is complete.


Function Sequence

JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.

function myFirst() {
  myDisplayer("Hello");
}

function mySecond() {
  myDisplayer("Goodbye");
}

myFirst();
mySecond();

Using a Callback

When you pass a function as a callback, remember not to use parentheses. You want to pass the function itself, not the result of the function.

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

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum); // The callback function is called here
}

myCalculator(5, 5, myDisplayer); 

When to use Callbacks?

The real power of callbacks comes in asynchronous programming. Where one function has to wait for another function (like waiting for a file to load or an API response).

  • Timers: setTimeout(myFunc, 3000).
  • Events: element.addEventListener("click", myFunc).
  • Data Fetching: Ensuring logic only runs after data has returned from the server.

Key Points to Remember

  • A callback is just a function name passed as a parameter
  • It allows for better asynchronous control
  • Pass the function name without parentheses
  • Callbacks ensure that certain code doesn’t execute until another has finished
  • They are the building blocks for Promises and Async/Await
  • Functions that accept callbacks are called Higher-Order Functions