DEV Community

Saman Mahmood
Saman Mahmood

Posted on

callback in JavaScript

Callbacks:

Definition:

A callback is a function that is passed as an argument to another function and is executed after the completion of a specific task. Callbacks are commonly used in asynchronous operations, such as handling events, making API requests, or reading files.

function fetchData(callback) {
  setTimeout(() => {
    const data = 'Callback Example Data';
    callback(data);
  }, 1000);
}

function processData(data) {
  console.log('Processing data:', data);
}

fetchData(processData);
Enter fullscreen mode Exit fullscreen mode

In this example, fetchData is a function that simulates an asynchronous operation. It takes a callback function (processData) as an argument and invokes it once the operation is complete.

Callback Hell (Callback Pyramids):
Callback hell refers to the situation where multiple nested callbacks create code that is hard to read and maintain. This occurs when dealing with deeply nested asynchronous operations.

Top comments (0)