What is a callback function in JavaScript

In JavaScript, a callback function is a function that is passed as an argument to another function, and it is then invoked inside that function. The main purpose of a callback function is to execute code that should only run after another function has finished its execution.

One of the most common uses of callback functions is in asynchronous programming.

Asynchronous programming is a programming paradigm where code is executed out of order, with certain parts of the code running independently from the rest of the program. This means that, in an asynchronous environment, code can continue to run while waiting for other operations to complete, without blocking the main thread.

Asynchronous functions in JavaScript, such as setTimeout() or XMLHttpRequest, take a callback function as an argument. When the asynchronous operation is complete, the callback function is called, allowing the program to continue executing.

Here is an example of how to use a callback function with setTimeout():

function sayHello() {
  console.log("Hello!");
}
setTimeout(sayHello, 1000);

In this example, the setTimeout() function takes two arguments: the first argument is the callback function, which is sayHello(), and the second argument is the time delay in milliseconds, which is 1000 (1 second). The sayHello() function is not executed immediately, but it is instead added to the event queue and executed after the specified delay.

Another common use case for callback functions is in event handling.

When an event occurs, such as a button click, a callback function can be used to handle the event and execute code in response.

Here is an example of how to use a callback function with event handling:

const button = document.querySelector("button");

button.addEventListener("click", function () {
  console.log("Button clicked!");
});

In this example, the addEventListener() function is used to add an event listener to the button element. The first argument is the event type, which is “click”, and the second argument is the callback function, which is an anonymous function that logs a message to the console.

One important thing to note about callback functions is that they can be synchronous or asynchronous.

Synchronous callback functions are executed immediately when the function they are passed to is called, while asynchronous callback functions are executed at a later time, after some other operation has completed.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: