What is a Callback Function?
A callback function is a function passed as an argument to another function and is executed after the completion of that function.
See the step-by-step examples below. Output is shown for each step.
function greet(name) {
return 'Hello, ' + name + '!';
}
let result1 = greet('Alice');
This is a regular function. It just returns a greeting string.
function processUserInput(name, callback) {
return callback(name);
}
This function takes a name and a callback function, and calls the callback with the name.
function sayGoodbye(name) {
return 'Goodbye, ' + name + '!';
}
let result2 = processUserInput('Bob', sayGoodbye);
Here, sayGoodbye is passed as a callback to processUserInput.
let result3 = processUserInput('Charlie', function(name) {
return 'Welcome, ' + name + '!';
});
An anonymous function is passed directly as a callback.
let result4 = processUserInput('Diana', name => 'Hi, ' + name + '!');
An arrow function is passed as a callback for concise syntax.