Javascript callback function

A callback function is a function passed into another function as an parameter, which is then invoked inside the outer function to complete some kind of action.




For example, we’ll write a function to check “user is eligible for voting or not” and pass a callback function as a parameter.

function checkUserEligible(age, callback) // here callback receive a callback function
  {
     if (age >= 18)
     callback(true);  // call callback function
      else
     callback(false); // call callback function
  }

checkUserEligible(10, function(response) { // response comes from callback method  i.e true or false
  if (response === true)
  console.log("Eligible for voting");
  else
  console.log("Not Eligible for voting");
  // Output Not Eligible for voting
});

checkUserEligible(18, function(response) { // response comes from callback method  i.e true or false
  if (response === true)
  console.log("Eligible for voting");
  else
  console.log("Not Eligible for voting");
  // Output Eligible for voting
});

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *