Callback in JavaScript

testYourselfJavaScript JavaScript3043 2 1

One of the most commonly used features in JavaScript is asynchronous operation support. In JavaScript, we have several methods to support asynchronous operations: callback, Promise, Observable.

Callbacks are the oldest JavaScript technique used to manage asynchronous operations. Callbacks in JavaScript can be used for asynchronous operations such as sending queries to the server and external api (e.g. Google API, Facebook API etc.), or listening for events (e.g. onClick, onMouseOver).

JavaScript callback is a function passed as an argument to another function for later execution.

Creating a callback

Callback in JavaScript is a typical function. It consists of a block of code placed in braces preceded by the function keyword, which will be executed after calling the function.

The use of anonymous functions is one of the common patterns used in callback functions.

function save(callback) {
    console.log('saving data...');
    callback();
}
save(function () {
    console.log('data has been saved');
});

Another popular pattern is the declaration of a named function and then pass the name of that function in the parameter.

function save(callback) {
    console.log('saving data...');
    callback();
}
function saved() {
    console.log('data has been saved');
}
save(saved);

When you define a parameter that will store the callback function, you don't have to use the word "callback", you can give it any name.

function save(foo) {
    console.log('saving data...');
    foo();
}
save(function () {
    console.log('data has been saved');
});

We can pass more than one callback function as a function argument, just as we can pass more than one variable. There are no restrictions on the number of callback functions.

function save(callback1, callback2) {
    console.log('saving data...');
    callback1();
    console.log('data has been saved');
    callback2();
}
save(function () {
    console.log('saving in progress');
}, function () {
    console.log('saving completed');
});

Executing a callback

When we pass callback as an argument to a function, we only pass its definition. To call a callback, use parentheses.

Because JavaScript callback is simply a normal function, we can pass any number of arguments to it during its execution. These arguments can then be used inside the function.

function save(callback) {
    console.log('saving data...');
    if (typeof callback === 'function') {
        callback(1);
    }
}

There is no limitation how many times we can execute a callback.

function save(callback) {
    console.log('saving data...');
    callback();
    callback();
}
save(function () {
    console.log('data has been saved');
});

It's always a good idea to check that the callback function passed in the parameter is actually the function before it was called. Without this check, calling a function without a parameter will cause an error.

function save(callback) {
    console.log('saving data...');
    if (typeof callback === 'function') {
        callback();
    }
}

It is also good practice to make the callback function optional.

Callback Hell

Callbacks in JavaScript are great for handling simple asynchronous operations, but they are not useful when you need to use several asynchronous operations, and the next operation depends on the success of the previous one.

isUserLoged(function (isLoged) {
    if (isLoged) {
        getUserData(function (data) {
            if (data.isPremium) {
                getPremiumContent(function (content) {
                    console.log(content);
                });
            }
        });
    }
});

The above example represents Callback Hell, that is multiple nesting of the callback functions. Such multiple nesting is illegible and makes the code difficult to interpret.

Summary

  • Callback is a function passed as an argument to another function for later execution.
  • JavaScript callback is a typical function that can be named or anonymous.
  • We can provide more than one callback function.
  • By calling the callback function we can pass any number of arguments to it.
  • There are no restrictions on the number of times we can call the callback function.
  • Callback Hell is a multiple nesting of callback functions.