Sometimes, you may want more control over when a function is executed.
For example, if you want to perform a calculation and then display the result, you could call a calculator function (myCalculator), store the result, and then call another function (myDisplayer) to show the result.
function myDisplayer(some) { document.getElementById(“demo”).innerHTML = some; } function myCalculator(num1, num2) { let sum = num1 + num2; return sum; } let result = myCalculator(5, 5); myDisplayer(result); |
Alternatively, you could call the calculator function (myCalculator) and have it call the display function (myDisplayer) itself.
function myDisplayer(some) { document.getElementById(“demo”).innerHTML = some; } function myCalculator(num1, num2) { let sum = num1 + num2; myDisplayer(sum); } myCalculator(5, 5); |
The issue with the first example is that you need to call two separate functions to display the result.
The problem with the second example is that the calculator function automatically displays the result, leaving you with no control over when it’s displayed.
This is where a callback comes in.