What is a Javascript Callback Function?

asdfasdf

When I was asked what a callback function was, I immediately thought of jQuery; as we so often pass a function as a parameter to a jQuery method. Most of the time, a passed in function will execute after the initial method’s code is complete.

jQuery’s onClick Function; a Callback method.

Examine the sample below of a pretty typical function call to jQuery’s onClick event, whereby you pass a function() as a parameter… The example below includes another call to the jQuery hide function which also passes in an anonymous function which will activate when the hide function has completed.

$( "#clickme" ).click(function() {
 
  //This call, passes a function to alert when the "hide" part is finished.
  $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
   });

});

We can conclude that the Callback pattern is ideal for responding to html events, like the onClick event of an html button. But, this isn’t the only use-case for when to use a Callback Javascript pattern. In addition, the setTimeout() and setInterval() are examples of built-in javascript methods which follow the Callback pattern. But additionally, we may want to take advantage of the Callback pattern in our our code, specifically when we find ourselves reusing a particular piece of code, over and over. Let me provide an example.

A simple callback function
function concatenateName(firstName, lastName, callback){

    //We alert the user's full name.         
    var fullname = firstName + " " + lastName;
    alert(fullname);

    //if the user passes in a function, and it is a function - fire it here.
    if (callback && typeof(callback) === "function") {
        callback(lastName);
    }

}
var greeting = function(lastName){
  console.log('Welcome Ms. ' + lastName);
};

//Call the function and pass in the "greeting" function which will log the person's name to the console.
//
fullName("Jerry", "Seinfeld", greeting);


Official Definition of Callback Function

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction.

When I’m coding I like to think of it as, passing in a piece of code that I would like to execute immediately after the function is complete.