JavaScript Callback functions

CodingTute

JavaScript

A callback function is a function that is passed as an argument to another function and is executed after the outer function has completed. Callback functions are often used in JavaScript to perform an action after an event has occurred, such as a button click or an HTTP request.

Here is an example of a callback function:

function greet(name, callback) {
  console.log("Hello, " + name);
  callback();
}

function sayGoodbye() {
  console.log("Goodbye!");
}

greet("John", sayGoodbye);

In this example, the greet function takes two arguments: a name and a callback function. The greet function logs a greeting to the console and then calls the callback function. The sayGoodbye function is defined as the callback function and logs a farewell message to the console. When the greet function is called, it logs “Hello, John” to the console and then calls the sayGoodbye function, which logs “Goodbye!” to the console.

Callback functions are often used in asynchronous programming, where a function may take some time to complete and we want to perform an action after it has completed. For example, when making an HTTP request, we can pass a callback function that is executed after the request has completed and the response has been received.

function getData(url, callback) {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.onload = function() {
    if (xhr.status === 200) {
      let data = JSON.parse(xhr.responseText);
      callback(data);
    }
  };
  xhr.send();
}

getData("http://example.com/data.json", function(data) {
  console.log(data);
});

In this example, the getData function makes an HTTP request to the specified URL and passes a callback function as an argument. When the response is received, the callback function is called with the data as an argument, and the data is logged to the console.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.