Understanding Callback Function

When we say callback, we always say okay, this is asynchronous call and it's not going to produce the result immediately but it will take some time to produce the result.
 
Usually callback mechanism used in case of expensive operation e.g. downloading file or performing I/O operations.
 
Generally callback in JavaScript is a function that is passed to another function (say it as anotherFunc) as a parameter and the callback function executed inside the anotherFunc. A callback function is also known as callback pattern.
Common callback code you might be seeing in JQuery.
  
$("buttonId").click(function(){
	alert("Button is clicked");
});
 
As you can see we are passing function inside click function and this function get executed by click method on click of button. The above example is typical use of callback function and widely being used in JQuery.
 
The typical example of callback is when we do Ajax call to server with method $.get() or $.post() method.
  
 $("buttonId").click(function(){
    $.get("any.jsp", function(data, status){
       // The function(data, status) is callback function here.
        alert("Data: " + data + "\nStatus: " + status);
    });
});
//Here is the Syntax for doing post call.

$.post(URL,data,callback);

Creating your own callback function 

<!DOCTYPE html>
<html>
    <head>
      
      <title>Callback function</title>
    </head>
    <body>
      <div id="divAdd" onclick="getInformation.add(10, 10);" 
	      style="height:10px; display:block;">; Add Click </div>
    </body>   

<script>
var getInformation = {
	"names": function () {
		alert("get the names");
	},
	"add" : function(x, y){
		alert(x+y);
	}
};

/**
names and add methods are being used as a callback function.
names function will get called at the time of page load 
and add function called on click of the div element.
*/

window.addEventListener("load", getInformation.names, false);

</script>

</html>
// Let's define an object with properties fullName and a method setFullName.
// We will later pass the method as a callback function to another function.
var formatName = {
    fullName: "",
    // set fullName by appending firstName and lastName.
    setFullName: function (firstName, lastName)  {
        // this refers to the fullName property in this object?
      this.fullName = firstName + " " + lastName;
    }
}

function getNameInfo(firstName, lastName, callback, callbackObj)  {
	// Do your application logic here.
  
//Here we are doing a call to the function being passed 
//as a parameter. Also it's a good practice to always check 
//for type before calling any callback method.
	 if (typeof callback === "function") 
		callback.apply(callbackObj, [firstName, lastName]);
}

getNameInfo("Deepak", "Singh", formatName.setFullName, formatName);

console.log (formatName.fullName);// Deepak Singh

 Hope this is useful and have given you an understanding of callback function.