What is a callback

suggest change

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, map calls double, the function the caller provided. 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 the function then accepts two callback functions, onFulfilled and onRejected. If the promise settles, only one of them is called. If it stays pending, neither is 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents