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.
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();
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);
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).
setTimeout(myFunc, 3000).element.addEventListener("click", myFunc).