What is a callback function? Why callback functions are useful?

A function that accepts other functions as arguments is called a high-order function, which holds the callback function to be effective.

What is a callback function?

In the JavaScript world, a callback is a function passed into another function as an argument and it will be executed later.

Callbacks are used in two ways: synchronous callback function, asynchronous callback function.

Example of callback function:

Following is the code segment to describe the callback function:

function create(name, callback) {
   console.log('Hi' + ' ' + name);
   callback();
}

// callback function
function callMe() {
   console.log('I am callback function');
}

// Passing function as an argument
create('Joe', callMe);

// Output:
Hi Joe
I am callback function

create is a high-order function it accepts two arguments, the second argument is callback. The callMe function is being used to enter us as a callback function.

Notice that we are not adding parentheses to callMe when we pass it as an argument. This is because we don’t want to run the callback function right now, we just want to pass the definition of the function to the high-order function so that it can be executed later.

Why callback functions are useful?

The callback function has many different use cases. Some of the uses cases have been discussed below:

Asynchronous data fetch

Most of the time we create programs and applications that work synchronously. In other words, some of our operations begin as soon as the previous tasks are completed.

Often when we request data from another source, such as an external API, we do not always know when our data will be returned.

In this case, we want to wait for a response, but we don’t always want our entire application to stop when we fetch our data. Callback functions come in handy in such situations.