JavaScript Callback Functions

The Callback functions are an important part of JavaScript. They are mostly used to run a function in response to the completion of a synchronous or asynchronous task. In this tutorial, we will learn what is a callback function, how to create one, the need for it and some of its use cases using examples

What is a Callback Function

JavaScript Callback function is a function that is passed as an argument to another function. Another function usually invokes the function when it finishes some task or completes some event.

How to create a Callback Function

In JavaScript, functions are special objects. We learned about JavaScript functions and about how to pass arguments to a JavaScript Function. The following code creates a function using function declaration.

Here sayHi is not only the name of the function but also a variable that stores the function. We invoke the function by passing arguments inside the parenthesis after the variable name. Since sayHi does not have any parameters, an empty parenthesis will suffice.

Since functions are objects we can assign it another a variable. And then use that variable to invoke the function.

This feature gives us the ability to pass a function as an argument to another function.

In the following code sayHi & welcome are regular JavaScript functions. The welcome function declares function as its parameter (f). It invokes the function by using the f().

We pass sayHi as the argument to the welcome function. The welcome function invokes the sayHi and displays the hi message.

In this example, sayHi is our callback function, because it is passed to welcome and invoked by it.

Note that, the following example, does the same thing, but it is not callback. Because in this case sayHi is fixed and cannot be changed.

The function is callback function only if we pass it in the argument of the function.

Need for Callback

The callback functions are many use cases. It is very useful in asynchronous actions. The asynchronous actions are those actions where JavaScript needs to wait for the action to complete.

For Example, waiting for the user to click on the button. We do not know when the user will click on the button. So we pass a callback function to the buttons click event. Whenever the user clicks the callback function is executed and we can respond to that.

CallBack Function Example

The following is one of the simple examples of callback.

We want our addNum to either print the result to console or show it an alert window based on some condition.

We create two functions. logToConsole prints the message to the console window, while logToAlert uses the alert window to display the message.

The addNum function takes the callback function as the third parameter. It invokes the callback function passing the result of addition as the argument. It does not care how the results are displayed.

We choose between logToConsole and logToAlert based on the value of someCond. If someCond is 1 then use the logToConsole else use the logToAlert.

This is one of the simple use cases for callback functions.

Here is another example of callback function. The operate operates on two numbers using the given callback function. You can pass addNum or multiplyNum to it

Callback to Array map method

The map() method of the array creates a new array after running the function on each element of the array.

In the example below, we multiply each element by 2 to create a new array in a callback function. The method below uses the arrow function as callback

The above example using regular function.

Asynchronous JavaScript

Responding to Asynchronous events is one of the important use cases for the callback functions.

In the following example, we use the setTimeout to mimic a Asynchronous event. The setTimeout has two parameters. a callback function and a time. It executes the callback function after the a specified time is passed.

In this example, it executes the sayHi callback function after a delay of 3000 ms.

CallBack Function Use cases

Callback functions are useful when you want to run a function in response to some event. Handling the browser event or responding to an HTTP request are the most common use cases.

Handling Browser Events

Web applications need to respond to events like button clicks, mouse movements, keyboard events, etc. We attach event handlers to respond to those events. These event handlers are nothing but callbacks

In the following example, we attach a function expression to the click event of the button element using the addEventListener method.

Alternatively, we can pass the Anonymous function directly, without declaring it

Responding to HTTP Requests

Sending HTTP Requests is another example of using callbacks. Here we use the fetch api to send the HTTP request. fetch API returns a promise, which is handled by the first callback. It converts it into a JSON and returns another promise. The second callback then displays the result in the console. If the fetch API errors out, it is handled by another callback in the catch method.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top