Callbacks are functions that are called within another function. Because functions in javascript can be passed around through variables, this makes it pretty painless.
function myFn(callbackFn) {
if (callbackFn) {
(callbackFn());
}
}Now we have a function that's ready to take a function as a parameter and call it. We can do many things to this, but lets start off simple.
myFn(function() {
alert('hi');
});This will call the function and pass an anonymous function as the call back. When it's executed within myFn() it will alert "hi".
No. You can pass function names as well.
function myOtherFn() {
alert('hello');
}
myFn(myOtherFn);Or even
var myOtroFn = function() {
alert('ohla');
};
myFn(myOtroFn);