DEV Community

Cover image for What is a Callback in Javascript?
Alan Mac Cormack
Alan Mac Cormack

Posted on

What is a Callback in Javascript?

Callbacks are usually an interview question and a must to understand if you want to be a web developer.

What is a callback?

In Javascript, functions are objects and that's the reason functions can take other functions as arguments and can also be returned by other functions.

The functions that take or return functions are called Higher-Order functions and the passed or returned ones are called Callback functions.

As an analogy we can say: A callback function is telling some other code to do some work, which will take some time. We don't get an answer immediately, so we say "when you've finished doing X, call function Y with the result".

How do we use callbacks?

function callback(message) { 
    alert(message); 
}

function higherOrderFunction(message, callback) {
    callback(message);      
}

higherOrderFunction('This is a callback test', callback);

Here, the callback function takes in an argument and shows an alert with the message as it's argument while higherOrderFunction takes in an argument and a callback function which will be executed with message as it argument.

Let's see some examples with different kind of functions.

Anonymous function:

This code will do exactly the same as our example above.


function higherOrderFunction(message, callbackFn) {
    callbackFn(message);        
}

higherOrderFunction("This is a message", function() {
    alert("message");
});

In this case the argument callbackFn that we pass can have any name you want since it's an anonymous function (has no name) that we are passing as argument to higherOrderFunction.

Arrow function:

function higherOrderFunction(message, callbackFn) {
    callbackFn(message);        
}

higherOrderFunction("This is a message", () => {
    alert("message");
});

What about DOM events?

Let's say we want to add an event listener to this button so when we click it, it shows an alert with a message:

<button id="show-message">Click here</button>

In our JS script we will use the addEventListener method passing to it 2 parameters, the type ("click") and the callback function will which show the alert message:

document.querySelector('#show-message')
    .addEventListener('click', function() {
        alert('This is a test message');
});

Why use Callback functions?

We mostly create apps that are synchronous. Basically, some of our operations will only start after the preceding one is completed.
In the real world we often request data from different sources as and external API and we don't know when the data will be delivered. We want to wait for the response, but we do not want our application stuck meanwhile.
In these situations is when callback functions are extremely handy.

You can find more info about callbacks in here

Latest comments (0)