Skip to main content

Command Palette

Search for a command to run...

Callbacks in JavaScript: Why They Exist

Updated
3 min read
Callbacks in JavaScript: Why They Exist

What is a Callback Function

A callback function is simply:
A function that is passed as an argument to another function and is executed later.

In simple words: “Function ke andar function bhejna, aur baad mein use chalana.”

Start with Functions as Values

In JavaScript, functions are treated like normal values.

That means:

  • you can store them in variables

  • you can pass them to other functions

Example:

function greet() {
  console.log("Hello");
}

function execute(fn) {
  fn(); // calling function
}

execute(greet);

Here:

  • greet is passed as a value

  • execute calls it

This is the basic idea of callback.

Passing Functions as Arguments

Example:

function processUser(name, callback) {
  console.log("Processing user:", name);
  callback();
}

function sayDone() {
  console.log("Done!");
}

processUser("Devesh", sayDone);

Output:

Processing user: Devesh
Done!

👉 Flow:

  1. Main function runs

  2. Then callback runs

Why Callbacks Are Used Main Reason

Callbacks are mainly used for asynchronous programming.
Problem
Some tasks take time:

  • API calls

  • file reading

  • database queries

  • timers

Example:

console.log("Start");

setTimeout(() = > {
  console.log("Task done");
}, 2000);

console.log("End");

Output:

Start
End
Task done

JavaScript does not wait So we need a way to run code after task completes
That’s where callbacks come in.

Callback in Async Scenario

function fetchData(callback) {
  setTimeout(() => {
    console.log("Data received");
    callback();
  }, 2000);
}

function processData() {
  console.log("Processing data");
}

fetchData(processData);

Flow:

  1. Data fetch starts

  2. After 2 seconds → callback runs

  3. Then processing happens

Common Use Cases of Callbacks

1. Timers

setTimeout(() => {
  console.log("Run after 2 sec");
}, 2000);

2. Event Handling

button.addEventListener("click", function() {
  console.log("Button clicked");
});

3. API Calls (Old style)

fetchData(function() {
  console.log("Data ready");
});

Basic Problem: Callback Nesting (Callback Hell )

When callbacks are nested too much, code becomes messy.

Example:

step1(function() {
  step2(function() {
    step3(function() {
      step4(function() {
        console.log("Done");
      });
    });
  });
});

Problems:

  • hard to read

  • hard to debug

  • looks like pyramid 😵

This is called:

Callback Hell

Conceptual Understanding of the Problem

  • Too many nested callbacks

  • Code moves to the right side (pyramid shape)

  • Difficult to maintain

That’s why modern JS uses:

  • Promises

  • async/await

Final Simple Understanding

  • Callback = function passed into another function

  • Used when we want something to run after a task finishes

  • Very important in async JavaScript