learn2kode.in

Callback functions in javascript

A callback is a function passed as an argument to another function, which is then executed later—usually after a task is completed.
Callbacks are commonly used for:
Call this function back when the work is done.

Why Are Callbacks Important?

JavaScript is single-threaded, meaning it can do only one thing at a time. Callbacks help JavaScript:

Without callbacks, JavaScript would freeze while waiting for tasks to complete.

Basic Callback Example

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

function sayBye() {
  console.log("Goodbye!");
}

greet("Alex", sayBye);
Output

Callback with Parameters

function calculate(a, b, callback) {
  const result = a + b;
  callback(result);
}

function display(result) {
  console.log("Result:", result);
}

calculate(5, 10, display);
Output

Callbacks in Asynchronous JavaScript

Example: setTimeout
setTimeout(function () {
  console.log("This runs after 2 seconds");
}, 2000);

Callbacks with Events

document.getElementById("btn").addEventListener("click", function () {
  alert("Button clicked!");
});

Callback Example with API Simulation

function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded successfully");
  }, 1500);
}

fetchData(function (message) {
  console.log(message);
});
Output

Callback Hell (Pyramid of Doom)

When callbacks are nested too deeply, the code becomes hard to read and maintain.
setTimeout(() => {
  console.log("Step 1");
  setTimeout(() => {
    console.log("Step 2");
    setTimeout(() => {
      console.log("Step 3");
    }, 1000);
  }, 1000);
}, 1000);
This is called Callback Hell.

Problems with Callbacks

This is why Promises and async/await were introduced.

Callbacks vs Promises

Feature Callbacks Promises / Async
Readability Low (nested) High
Error handling Complex Simple (catch)
Modern usage Limited Preferred
Control flow Hard Clean

When Should You Use Callbacks?

Avoid for complex async flows (use Promises instead)

Real-World Use Cases of Callbacks

Key Takeaways