how to use javascript callback functionn code example
Example 1: javascript callback
/*
A callback function is a function passed into another function
as an argument, which is then invoked inside the outer function
to complete some kind of routine or action.
*/
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
// The above example is a synchronous callback, as it is executed immediately.
Example 2: callback function
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2
}
function logQuote(quote){
console.log(quote);
}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!
Example 3: callback function js
function myDisplayer(some) { document.getElementById("demo").innerHTML
= some;}function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);}myCalculator(5, 5, myDisplayer);