Callbacks & Callback Hell

Published by Brayan K

A callback is just a function you hand to another function to run later. It's the original way JavaScript handled "do this when the work is done" — clicks, timers, file reads, network requests — and it's still everywhere.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A callback is a function value; its caller decides the timing

A callback does not necessarily run later: the receiving function may invoke it before returning, defer it, invoke it several times or never invoke it. The opening description’s “later” includes deferred work, but timing is part of the particular API contract, not a property of every callback.

function makeLabel(item, formatter) {
  console.log("inside makeLabel");
  // The function value is called here, with the item as its argument.
  const formatted = formatter(item);
  // This helper deliberately uses the callback return value.
  return "Item: " + formatted;
}
console.log("before");
const result = makeLabel("a17", value => {
  console.log("inside formatter");
  return value.toUpperCase();
});
console.log(result);
console.log("after");

// ✅ Expected output:
// before
// inside makeLabel
// inside formatter
// Item: A17
// after

Passing a function lets another function choose when to invoke it and what arguments to supply. Functions owns parameters and return values; this lesson follows who calls whom and where the result goes.

Pass the function, or wrap a call you want to make later

Writing parentheses invokes a function now. If a receiver expects a callback, the value returned by that immediate invocation may be the wrong type. A wrapper can supply extra arguments when the receiver eventually calls it.

function format(value) {
  return value.toUpperCase();
}
function run(callback) {
  return callback("a17");
}
console.log(run(format("b24")));

// ✅ Expected error:
// TypeError: callback is not a function
function format(value, prefix) {
  return prefix + value.toUpperCase();
}
function run(callback) {
  return callback("a17");
}
console.log(run(value => format(value, "Item ")));

// ✅ Expected output:
// Item A17

The wrapper is a function value until run calls it. The this Keyword owns the separate issue of preserving an object receiver when passing a method.

A callback return only reaches the code that calls it

A callback can return a value, but the receiving API decides whether to use that return. Returning from the callback does not automatically return from every enclosing function. Compare these two ordinary helpers.

function keep(callback) {
  return callback(3);
}
function discard(callback) {
  callback(3);
}
const double = value => value * 2;
console.log(keep(double));
console.log(discard(double));

// ✅ Expected output:
// 6
// undefined
function forEachLabel(labels, callback) {
  for (const label of labels) {
    callback(label);
  }
}
let calls = 0;
forEachLabel(["A17", "B24"], label => {
  calls += 1;
  console.log(label);
  return "ignored";
});
forEachLabel([], () => { calls += 1; });
console.log(calls);

// ✅ Expected output:
// A17
// B24
// 2

Read the API’s arguments, timing, return handling and call-count contract together. map, filter & reduce owns how the array methods use callback returns.

Deferred work cannot fill an already returned result

The following examples use queueMicrotask only to schedule a callback after the current synchronous work. Event Loop, Microtasks & Async Internals owns queue ordering; no timer duration or network response is involved here.

console.log("before");
queueMicrotask(() => {
  console.log("callback");
});
console.log("after");

// ✅ Expected output:
// before
// after
// callback
function readScore() {
  let score;
  queueMicrotask(() => {
    score = 8;
    console.log("assigned", score);
  });
  return score;
}
console.log("returned", readScore());

// ✅ Expected output:
// returned undefined
// assigned 8
function readScore(callback) {
  queueMicrotask(() => callback(8));
}
readScore(score => {
  console.log("doubled", score * 2);
});
console.log("request scheduled");

// ✅ Expected output:
// request scheduled
// doubled 16

Changing let to var, or adding a return inside the deferred callback, would not move that callback before the outer return. Place dependent work in the callback or use an asynchronous result contract. Async/Await owns consuming promise-based results.

An error-first callback is a convention you must implement

In an error-first contract, the first argument describes a failure or is null on success, and the following argument carries the successful value. This is an ordinary function call convention, not syntax that JavaScript enforces automatically. Check the error before reading result fields.

function readItem(id, callback) {
  if (id !== "A17") {
    callback(new Error("Item not found"), undefined);
    return;
  }
  callback(null, { id, quantity: 3 });
}
function showItem(error, item) {
  if (error) {
    console.log("failed", error.message);
    return;
  }
  console.log("loaded", item.id, item.quantity);
}
readItem("A17", showItem);
readItem("missing", showItem);

// ✅ Expected output:
// loaded A17 3
// failed Item not found
function brokenRead(id, callback) {
  if (id !== "A17") {
    callback(new Error("Item not found"), undefined);
  }
  callback(null, { id, quantity: 3 });
}
brokenRead("missing", (error, item) => {
  console.log(error ? "failure" : "success");
});

// ✅ Expected output:
// failure
// success

For a one-result operation, return after delivering a failure so execution cannot fall through into the success callback. Repeating notifications can be intentional in another API; the problem here is violating this particular one-result contract.

A surrounding try cannot catch a callback after it has finished

Try/catch handles exceptions thrown while its try block is executing. Scheduling a callback inside that block does not keep the catch waiting for the later callback. The following complete program prints its scheduling message and then fails.

try {
  queueMicrotask(() => {
    throw new Error("Deferred failure");
  });
} catch (error) {
  console.log("outer caught", error.message);
}
console.log("scheduled");

// ✅ Expected output:
// scheduled

// ✅ Expected error:
// Error: Deferred failure
queueMicrotask(() => {
  try {
    throw new Error("Deferred failure");
  } catch (error) {
    console.log("callback caught", error.message);
  }
});
console.log("scheduled");

// ✅ Expected output:
// scheduled
// callback caught Deferred failure

An error passed as a callback argument is not automatically thrown either. Follow the API’s documented error channel. Error Handling owns exception boundaries and recovery decisions.

Name dependent stages without changing their sequence

When the next operation needs a result from the previous operation, invoke it from that operation’s completion path. Giving stages names can reduce nesting, but names alone do not change timing, stop duplicate completion or handle failures.

function stage(label, done) {
  queueMicrotask(() => {
    console.log(label);
    done();
  });
}
function afterLoad() {
  stage("validate", afterValidate);
}
function afterValidate() {
  console.log("ready");
}
stage("load", afterLoad);
console.log("started");

// ✅ Expected output:
// started
// load
// validate
// ready

These are fixed local demonstration steps, not file or network requests. Promise-based composition offers another way to express dependencies and failure flow; Mastering Promises: Chaining, Error Flow & Patterns owns that separate contract. Callbacks still remain useful in array operations, listeners and APIs that explicitly expect them.

Pass the handler instead of invoking it

The helper schedules one callback with a score. Fill the function-value blank using the literal hint. Do not add parentheses: the helper will supply the score when it invokes your handler.

function deliver(callback) {
  queueMicrotask(() => callback(8));
}
const onScore = score => console.log("score", score);
deliver(___);
// 👉 replace ___ with onScore
console.log("waiting");

// ✅ Expected output:
// waiting
// score 8

Build a result only after both successful callbacks

Write buildLabel(id, done) using error-first callbacks. Build local deferred fixtures with these contracts: loadItem accepts A17 and B24, but reports Item not found for any other identifier; readQuantity returns 3 for A17 and reports Quantity unavailable for B24. Load the item before reading its quantity, then deliver an item-and-quantity label. On either error, deliver that error once and stop that path. Check A17, a missing item and B24 in sequence; the missing item must not trigger a quantity request.

let quantityRequests = 0;
function loadItem(id, done) {
  queueMicrotask(() => {
    if (id !== "A17" && id !== "B24") {
      done(new Error("Item not found"), undefined);
      return;
    }
    done(null, { id });
  });
}
function readQuantity(item, done) {
  quantityRequests += 1;
  queueMicrotask(() => {
    if (item.id === "B24") {
      done(new Error("Quantity unavailable"), undefined);
      return;
    }
    done(null, 3);
  });
}
function buildLabel(id, done) {
  loadItem(id, (itemError, item) => {
    if (itemError) {
      done(itemError, undefined);
      return;
    }
    readQuantity(item, (quantityError, quantity) => {
      if (quantityError) {
        done(quantityError, undefined);
        return;
      }
      done(null, item.id + ": " + quantity);
    });
  });
}
buildLabel("A17", (error, label) => {
  console.log(error ? error.message : label);
  buildLabel("missing", (error, label) => {
    console.log(error ? error.message : label);
    buildLabel("B24", (error, label) => {
      console.log(error ? error.message : label);
      console.log("quantity requests", quantityRequests);
    });
  });
});

// ✅ Expected output:
// A17: 3
// Item not found
// Quantity unavailable
// quantity requests 2

The checks exercise successful completion, a missing item and a failed quantity lookup. The count shows that an item failure stops the dependent request. The sample is a control-flow exercise with local fixtures, not an implementation of a database or network client.

References: MDN callback functions, MDN microtasks and Node error-first callback conventions.

Practice quiz

What does this complete program print? function run(callback) { return callback(3) + 1; } console.log(run(value => value * 2));

  • 7
  • 6
  • 4
  • undefined

Answer: 7. The helper uses the callback return and then adds one.

What does this complete program print? function run(callback) { callback(3); } console.log(run(value => value * 2));

  • 6
  • undefined
  • 3
  • TypeError: callback is not a function

Answer: undefined. This helper discards the callback result and has no return statement.

What does this complete program print? console.log("before"); queueMicrotask(() => console.log("callback")); console.log("after");

  • before callback after
  • callback before after
  • before after callback
  • before after

Answer: before after callback. The current synchronous work completes before the queued callback runs.

What does this complete program print? function getValue() { let value = 1; queueMicrotask(() => { value = 9; }); return value; } console.log(getValue());

  • 9
  • undefined
  • ReferenceError: value is not defined
  • 1

Answer: 1. The return reads the value before the queued assignment.

What does this complete program print? function read(done) { done(new Error("missing"), undefined); } read((error, value) => console.log(error ? error.message : value));

  • missing
  • undefined
  • Error: missing
  • null

Answer: missing. The Error is passed as data, and the callback deliberately prints its message.

What does this complete program print? function read(done) { done(new Error("missing")); done(null, 8); } read(error => console.log(error ? "failure" : "success"));

  • failure
  • failure success
  • success
  • success failure

Answer: failure success. There is no return after the failure callback, so the helper invokes the callback again.

Which error ends this program? function make() { return "ready"; } function run(callback) { return callback(); } console.log(run(make()));

  • ReferenceError: make is not defined
  • SyntaxError: Unexpected token
  • TypeError: callback is not a function
  • RangeError: Maximum call stack size exceeded

Answer: TypeError: callback is not a function. Make is called immediately, so run receives a string rather than a function.

What does this complete program print? let calls = 0; function twice(callback) { callback(); callback(); } twice(() => { calls += 1; }); console.log(calls);

  • 0
  • 1
  • undefined
  • 2

Answer: 2. The receiver calls the supplied function twice; the word callback does not imply exactly one call.

Continue this course

Related lessons