Skip to main content

Command Palette

Search for a command to run...

Callbacks in JavaScript: Why They Exist

Updated
2 min read
Callbacks in JavaScript: Why They Exist

A callback is a function you pass into another function so that it can decide when to run it. Not immediately Only when the outer function chooses.

function greet(name) {
  return `Hello, ${name}`;
}

function processUserInput(callback) {
  const name = "Rachit";

  // callback is just a function reference here
  // we decide when to execute it
  return callback(name);
}

// passing function, not calling it
const result = processUserInput(greet);

console.log(result); // Hello, Rachit

Why Callbacks Exist

JavaScript doesn’t wait around for slow tasks.If something takes time, like a network request or delay, blocking the whole program is a bad idea.So instead of waiting, we say: “Run this function when you're done.” That “this function” is the callback.

Where You Actually Use Callbacks

Callback functions are primarly used in async functions where we send rquest to other network or you could say when promise is resolved the callback is calleld

function fetchData(callback) {
  console.log("Fetching data...");
  setTimeout(() => {
    const data = { id: 1, name: "Rachit" };

    callback(data);
  }, 2000);
}

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

console.log("This runs first");

The Problem: Callback Hell

Callbacks scale badly when tasks depend on each other.

setTimeout(() => {
  console.log("Step 1");

  setTimeout(() => {
    console.log("Step 2");

    setTimeout(() => {
      console.log("Step 3");

      // this keeps going...
    }, 1000);

  }, 1000);

}, 1000);

What’s wrong here:

  • Hard to read

  • Hard to debug

  • Error handling becomes messy

  • Logic gets buried inside nesting

This is what people call “callback hell.”

What Comes Next

Callbacks aren’t wrong. They’re just not scalable.

That’s why JavaScript moved to:

  • Promises

  • async/await

JS Under the Hood: The Engine Room

Part 15 of 24

Ever wondered why your code actually runs? We’re going beyond the syntax to explore the V8 engine, memory management, and the "magic" that happens between your keyboard and the screen. Just deep dives.

Up next

JavaScript Promises Explained for Beginners

1. The Core Concept: A Future Value The best way to understand a Promise is to think of it like a restaurant buzzer. When you order food at a busy restaurant, they don't give you your food immediately