logic - When to use calling javascript functions as parameter and its advantages -


i have learnt new thing/concept in javascript. calling function using function parameter, please have @ fiddle examples

passing function parameter

progressbar(1, 2, function() { flag=true; console.log(' after flag : '+flag);}, flag); 

normal function.

progressbar(1, 2, flag); 

looking @ console statements have understood effect, little confused concept prove important/useful.

javascript async language , compiler continuously read next line , not wait returning value of function. in case, if our operation depends in other operation cannot achieve using simple function in "javascript".

like say, in creating examination mark-sheet. need have total or sum value of subject's obtained marks. after calculating total able calculate percentage , if don't have total marks cannot calc percentage.

example :

function getobtainedmarks(student_id){ //get total marks server , 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 above example, final value of percentage undefined because when called getobtainedmarks, calculating total sending request server in mean time compiler moved next statement i.e var percentage = calcpercentage(obtained_marks,total_marks);

so, here javascript introduces callback functions, bind our operation on dependent operations.

for example:

function getobtainedmarks(student_id,callback){ //get total marks server , 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 above example, calcpercentage(obtained_marks,total_marks) not call until getobtainedmarks callback value of of obtained_marks. so, difference between these 2 kind of functions in javascript , posted example guidance.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -