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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay