Thursday, 8 March 2018

example of callback function

A callback is a plain javascript function passed to the some function as a argument or option.Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

Case -1

let x = function(){
   console.log('called from inside the function');
};

let y = function(callback){
   console.log('do something');
   callback();
};

y(x) //(index):54 do something
     // called from inside the function
   
  Case -2

   let calculate =function(num1, num2 , calltype){

   if(calltype === 'add'){
     return num1 + num2;
   }else if(calltype === 'multiply'){
     return num1 * num2;
   }
}
   
   
console.log(calculate(2,3, 'add')); //5

console.log(calculate(2,3, 'multiply')); //6

case-3

//better way to implement callback function

let add = function(num1, num2){
   return num1 + num2;
}

let multiply = function(num1, num2){
   return num1 * num2;
}

let dowork = function(num1, num2){
   console.log(`here are two numbers back ${num1} , ${num2}`);
}

let calculate = function(num1, num2, callback){
  return callback(num1, num2);
}
   
   
console.log(calculate(2,3, add)); //5

console.log(calculate(2,3, multiply)); //6

console.log(calculate(2,3, dowork)); //here are two numbers back 2 , 3

console.log(calculate(2,3, function(x,y){ return x-y})); //-1

case -4  //sorting array by call back function

var array =[
             {num:5, str:'apple'},
             {num:7, str:'cabbage'},
             {num:1, str:'ban'}
            ]
         
     array.sort(function(val1 , val2){
   
        //console.log(val1.str);
        //console.log(val2.str);
   
        if(val1.str < val2.str ){
         return -1;
        }else{
          return 1;
        }
     });
   
     console.log(array);
   
         






No comments:

Post a Comment