Labs ICT
🎓 SIWES/IT Login

Callbacks

1 min read | JavaScript Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

What is a Callback?

A callback is a function passed into another function as an argument, then executed inside the outer function. Callbacks are essential for asynchronous programming in JavaScript.

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

function afterGreet() {
  console.log("Callback executed!");
}

greet("Alice", afterGreet);

Async with Callbacks

Callbacks shine with async operations like timers or file reads. Here's a simulated async task using setTimeout:

function fetchData(callback) {
  setTimeout(() => {
    const data = { id: 1, name: "Item" };
    callback(data);
  }, 1000);
}

fetchData((result) => {
  console.log("Data received:", result);
});

Callback Hell

Nesting too many callbacks creates "callback hell" — hard-to-read pyramid code. Promises solve this.

setTimeout(() => {
  console.log("Step 1");
  setTimeout(() => {
    console.log("Step 2");
    setTimeout(() => {
      console.log("Step 3");
    }, 500);
  }, 500);
}, 500);