Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Created June 2, 2017 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnewman12/fb6c2c0e5cb4bc3b99994b312fb980e5 to your computer and use it in GitHub Desktop.
Save jnewman12/fb6c2c0e5cb4bc3b99994b312fb980e5 to your computer and use it in GitHub Desktop.

What is a Callback?

A reference to executable code, or a piece of executable code, that is passed as an argument to other code.

All a callback is, is a function that takes a function as an argument.

Here is an example

function mySandwich(param1, param2, callback) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    callback();
}

mySandwich('ham', 'cheese', function() {
    alert('Finished eating my sandwich.');
});

Here we have a function called mySandwich and it accepts three parameters. The third parameter is the callback function. When the function executes, it spits out an alert message with the passed values displayed. Then it executes the callback function.

Callbacks are generally optional.

function mySandwich(param1, param2, callback) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    if (callback) {
        callback();
    }
}

mySandwich('ham', 'cheese');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment