J

JavaScript Handbook

Clean • Professional

Callbacks in JavaScript

1 minute

Callbacks in JavaScript

A callback is a function that is passed as an argument to another function and is executed later, usually after an asynchronous operation has finished.

Callbacks are one of the fundamental ways to handle asynchronous behavior in JavaScript — for example, waiting for a timer, network request, or file to finish loading.

How Callbacks Work

JavaScript executes code synchronously (line by line).

If you perform a time-consuming operation (like fetching data from a server), it could block other code.

To prevent this, JavaScript uses callbacks to defer execution of certain code until a task is completed.

Example: Simple Callback

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

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

greet("Alice", sayGoodbye);

Example: Asynchronous Callback (setTimeout)

console.log("Start");

setTimeout(() => {
  console.log("This runs after 2 seconds");
}, 2000);

console.log("End");

Callback Hell

When callbacks are nested inside each other, the code becomes hard to read and maintain — this is called callback hell or pyramid of doom.

Example:

setTimeout(() => {
  console.log("Step 1");
  setTimeout(() => {
    console.log("Step 2");
    setTimeout(() => {
      console.log("Step 3");
    }, 1000);
  }, 1000);
}, 1000);

Avoiding Callback Hell

Callback hell can be avoided by using:

  • Named functions instead of anonymous callbacks.
  • Promises and Async/Await, which make code more readable and maintainable.

Example using Promises:

fetch("<https://api.example.com/data>")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Summary Table

ConceptDescriptionExample
CallbackFunction passed as an argument and executed latersetTimeout(() => {...}, 1000)
Synchronous CallbackRuns immediatelyarr.forEach(cb)
Asynchronous CallbackRuns after a delay or async tasksetTimeout(cb, 1000)
Callback HellNested callbacks that reduce readabilityMultiple setTimeout calls
Modern AlternativesPromises, Async/AwaitCleaner async handling

 

Article 0 of 0