how do callback functions work in javascript code example
Example 1: javascript callback
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
Example 2: javascript callback
function newCallback(callback) {
callback('This can be any value you want to return')
}
function actionAferCallback (callbackData) {
console.log(callbackData)
}
function requestCallback() {
newCallback(actionAferCallback)
}
Example 3: create callback function javascript
function add(a, b, callback) {
if (callback && typeof(callback) === "function") {
callback(a + b);
}
}
add(5, 3, function(answer) {
console.log(answer);
});
Example 4: callback in js
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback , {
var name = prompt('Please enter your name.');
callback(name);
}}
processUserInput(greeting);
Example 5: js callback function
const add = (num1, num2) => num1 + num2;
const result = (num1, num2, cb) => {
return "result is:" + cb(num1, num2);
}
const res = result(12, 13, add);