[javascript] Getting a better understanding of callback functions in JavaScript

You can use:

if (callback && typeof(callback) === "function") {
    callback();
}

The below example is little more comprehensive:

_x000D_
_x000D_
function mySandwich(param1, param2, callback) {_x000D_
  alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);_x000D_
  var sandwich = {_x000D_
      toppings: [param1, param2]_x000D_
    },_x000D_
    madeCorrectly = (typeof(param1) === "string" && typeof(param2) === "string") ? true : false;_x000D_
  if (callback && typeof(callback) === "function") {_x000D_
    callback.apply(sandwich, [madeCorrectly]);_x000D_
  }_x000D_
}_x000D_
_x000D_
mySandwich('ham', 'cheese', function(correct) {_x000D_
  if (correct) {_x000D_
    alert("Finished eating my " + this.toppings[0] + " and " + this.toppings[1] + " sandwich.");_x000D_
  } else {_x000D_
    alert("Gross!  Why would I eat a " + this.toppings[0] + " and " + this.toppings[1] + " sandwich?");_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to callback

When to use React setState callback How to send an HTTP request with a header parameter? javascript function wait until another function to finish What is the purpose of willSet and didSet in Swift? How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? Aren't promises just callbacks? How do I convert an existing callback API to promises? How to access the correct `this` inside a callback? nodeJs callbacks simple example Callback after all asynchronous forEach callbacks are completed