Labs ICT
Pro Login

Callbacks

1 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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);