What is a Callback?
A reference to executable code, or a piece of executable code, that is passed as an argument to other code.
All a callback is, is a function that takes a function as an argument.
Here is an example
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}
mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});
Here we have a function called mySandwich and it accepts three parameters. The third parameter is the callback function. When the function executes, it spits out an alert message with the passed values displayed. Then it executes the callback function.
Callbacks are generally optional.
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
if (callback) {
callback();
}
}
mySandwich('ham', 'cheese');