Are javascript callbacks just anonymous functions sent as an argument in a function call?

javascript

Solution

JavaScript callbacks are functions passed as values into an asynchronous function for the purpose of continuation.

Functions are values:

So in JavaScript, you can pass a functions around like values. You can reference a function in a number of ways:

Pass a literal anonymous function as the callback

doSomeWork(function (err, result) {
    if (err) {
        throw new Error(err);
    } else {
        console.log(result);
    }
});

Pass a literal named function as the callback

doSomeWork(function magicalCallback(err, result) {
    if (err) {
        throw new Error(err);
    } else {
        console.log(result);
    }
});

(Naming every function is a smart idea because you can see it in the stack trace)

Pass in the value of a variable which happens to be storing a function as the callback

var someFunction = function callItWhatYouWant(err, result) {
    if (err) {
        throw new Error(err);
    } else {
        console.log(result);
    }
}

// reference the callback stored in the someFunction variable
doSomeWork(someFunction);

Pass in the function by referencing the function name as the callback

function callItWhatYouWant(err, result) {
    if (err) {
        throw new Error(err);
    } else {
        console.log(result);
    }
}

// reference the callback function using the function name
doSomeWork(callItWhatYouWant);

Continuation?

Continuation is all about the next step. When you call a function which is asynchronous, it needs to notify you that it is done. The callback acts as the next step, i.e. the asynchronous function will call you back when it is done.

So a callback is just a function argument used for a particular purpose, that being, continuation.

Callback signature

There is no standard for which arguments a callback should take, but in the Node.js community we have adopted the general signature

function (err, result)

where `err` is an `Error` object if something bad happened, or `null` if things were successful. If things went bad `result` is generally `undefined`, otherwise it contains the result. So your callback is generally called by either

callback(new Error("oops"));

or

callback(null, result);

Also note that it's normal for the last parameter of an asynchronous function to be the callback parameter

function callLater(delay, args, callback) {
    setTimeout(function () {     
        callback(null, args);
    }, delay);
}

Problem

Are `Javascript` `callbacks` just anonymous functions sent as an argument in a function call? For example, ``` mySandwich('ham', 'cheese', function() { alert('Finished eating my sandwich.'); }); ```

Original source