Callbacks: The Old Way

Callbacks: The Old Way in JavaScript: A callback is simply a function that you pass into another function to be run later.

Concept Explanation

A callback is simply a function that you pass into another function to be run later.

Before Promises, this was the only way to do async work. But it had a dark side: Callback Hell. If you needed to do 5 things in a row, your code would crawl towards the right side of the screen in a mountain of nested braces.


Syntax or Core Structure

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

// Using the callback
fetchData((user) => {
    console.log(`Received user: ${user.name}`);
});

Common Mistakes

  1. Callback Hell: Nesting 4 levels deep. It's impossible to debug or read.
  2. Error Handling: If an error happens inside an async callback, a normal try/catch won't catch it! You have to pass the error as an argument to the callback manually.
  3. Inversion of Control: You are giving your function to someone else's code. What if they call it twice? Or never call it? This "trust" issue led to the invention of Promises.

Best Practices

  • Node-style Callbacks: Always make the first argument of your callback the error: callback(err, result).
  • Name your functions: Don't use anonymous functions for everything. Naming your callbacks makes the stack trace much easier to read during a crash.
  • Move to Promises: If you're writing a new app in 2026, avoid raw callbacks for async work. Use Promises or Async/Await.

Practice Exercises

  1. The Error First: Write a simulation function that "fetches data" but fails 50% of the time. Use a Node-style (err, data) callback to handle both cases.
  2. The Nesting Trap: Write a sequence where you "Login", then "Get Profile", then "Get Posts" using only callbacks. Notice how messy it gets!
  3. The Array Classic: Use the .map() method. Explain why the function you pass into .map() is actually a callback!