Callback function

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

Here is a quick example:

function greeting(name) {
  alert('Hello ' + name);
}
function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}
processUserInput(greeting);

The above example is a synchronous callback, as it is executed immediately.

Note however that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. For example, our simple maps-example.html example (see it live also) uses the Google Maps API and Geolocation API to display a map of your device's current location.

Because getting the device's coordinates from its GPS is asynchronous (we don't know exactly when the data will be returned), the Geolocation.getCurrentPosition() method takes an anonymous callback function as a parameter, which itself takes the returned coordinate data as a parameter. This function is only executed when the coordinate data is returned. 

Learn more

General knowledge

Document Tags and Contributors

 Last updated by: netpoetica,