• Post category:JavaScript
  • Reading time:2 mins read

In JavaScript, a callback function is a function that is passed as an argument to another function and is invoked or called when a specific event or condition occurs. It allows for asynchronous execution and helps manage control flow in situations where the order of execution cannot be determined beforehand.

Here’s an example to illustrate the concept of a callback function:

function fetchData(url, callback) {
  // Simulating an asynchronous operation
  setTimeout(function() {
    const data = { id: 1, name: 'John Doe', age: 25 };
    callback(data); // Invoke the callback function with the fetched data
  }, 2000); // Simulating a 2-second delay

function displayData(data) {
  console.log('Received data:', data);
  // Perform further actions with the received data

// Usage: Pass the displayData function as a callback to fetchData
fetchData('https://example.com/api/data', displayData);

In the above example, we have two functions: fetchData and displayData. The fetchData function is responsible for fetching data from a URL asynchronously. It takes a URL and a callback function as arguments. After a 2-second delay (simulated with setTimeout), it invokes the callback function with the fetched data.

The displayData function is passed as a callback to fetchData. It receives the fetched data as a parameter and performs some actions, in this case, logging the received data to the console.

By using a callback function, we can ensure that the displayData function is only executed after the data is successfully fetched, allowing us to handle asynchronous operations and control the flow of our program.

Callbacks are commonly used in JavaScript for handling events, making HTTP requests, working with timers, and other scenarios where the order of execution is not deterministic. They provide a way to execute code when certain operations are complete or conditions are met, enabling asynchronous programming and improving overall flexibility.

Happy Coding!

Leave a Reply