A JavaScript callback function is a function passed into another function as a parameter.
Using a callback, you could call another function with a callback, and let the first function run the callback after all statements completed.
JavaScript callback function Example
In the HTML example, addNum function accept 3 parameter. Where is 3rd parameter is callback function – displayResult.
So what is happening:-
First addNum will finish the addition of 2 number, then it will call the displayResult function to show the result.
<html>
<body>
<p>Addition of numebr is: </p>
<p id="demo"></p>
<script>
function displayResult(some) {
document.getElementById("demo").innerHTML = some;
}
function addNum(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
// Test case
addNum(10, 5, displayResult);
</script>
</body>
</html>
Output:
Q: When to Use a JavaScript Callback function?
Answer: The benefit of using a JS callback function is that you can wait for the result of a previous function call and then execute another function call.
Do comment if you have any doubts and suggestion on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version