JavaScript is async language and compiler continuously read the next line and do not wait for returning value of the function. So in that case, if our operation depends in some other operation then we cannot achieve this by using simple function in "JavaScript".
Like I say, in creating examination mark-sheet. I need to have total or sum value of all subject's obtained marks. After calculating the total I will be able to calculate percentage and if I don't have total marks then I cannot calc percentage.
Example :
function getObtainedMarks(student_id){
//get the total marks from server and it takes little more time
return obtained_marks;
}
function calcPercentage(obtained_marks,total_marks){
return ((obtained_marks/total_marks)*100);
}
var total_marks = 500; var obtained_marks = getTotalMarks(101);
var percentage = calcPercentage(obtained_marks,total_marks);
in the above example, the final value of percentage
would be undefined
because when we called getObtainedMarks
, it was calculating the total by sending request to server but in the mean time compiler moved to next statement i.e var percentage = calcPercentage(obtained_marks,total_marks);
So, here JavaScript introduces callback functions, we actually bind our operation on some dependent operations.
For Example:
function getObtainedMarks(student_id,callback){
//get the total marks from server and it takes little more time
callback(obtained_marks);
}
function calcPercentage(obtained_marks,total_marks){
return ((obtained_marks/total_marks)*100);
}
var total_marks = 500;
getTotalMarks(101,function(obtained_marks){
var percentage = calcPercentage(obtained_marks,total_marks);
});
In the above example, calcPercentage(obtained_marks,total_marks)
will not call until getObtainedMarks
callback the value of of obtained_marks
. So, this is the difference between these 2 kind of functions in JavaScript and I also posted the example for your guidance.