JavaScript What is a callback?


This is a normal function call:

console.log("Hello World!");

When you call a normal function, it does its job and then returns control back to the caller.

However, sometimes a function needs to return control back to the caller in order to do its job:

[1,2,3].map(function double(x) {
    return 2 * x;

In the above example, the function double is a callback for the function map because:

  1. The function double is given to the function map by the caller.
  2. The function map needs to call the function double zero or more times in order to do its job.

Thus, the function map is essentially returning control back to the caller every time it calls the function double. Hence, the name “callback”.

Functions may accept more than one callback:

promise.then(function onFulfilled(value) {
    console.log("Fulfilled with value " + value);
}, function onRejected(reason) {
    console.log("Rejected with reason " + reason);

Here then function then accepts two callback functions, onFulfilled and onRejected. Furthermore, only one of these two callback functions is actually called.

What's more interesting is that the function then returns before either of the callbacks are called. Hence, a callback function may be called even after the original function has returned.