Skip to content

Instantly share code, notes, and snippets.

@jnewman12 jnewman12/note.md
Created Jun 2, 2017

Embed
What would you like to do?

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
You can’t perform that action at this time.