On this page

JavaScript Callbacks

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. In the context of asynchronous JavaScript, callbacks serve as the original mechanism for ensuring that specific code does not execute until an asynchronous operation has finished.

The Mechanism of Callbacks​

Because JavaScript is event-driven and non-blocking, it will not wait for a response from an external source (like a database or a file system) before moving to the next line of code. Callbacks provide a way to say: "Once you have finished this long-running task, execute this specific function."

Synchronous vs. Asynchronous Callbacks​

It is important to distinguish between the two ways callbacks are used:

  1. Synchronous Callbacks: These are executed immediately during the execution of the higher-order function. A common example is the .forEach() method used on arrays.
  2. Asynchronous Callbacks: These are placed in the Task Queue and executed only after the Call Stack is empty. Examples include setTimeout handlers or data-loading events.

function fetchData(callback) {

  console.log("Fetching data...");



  // Simulating an asynchronous network request

  setTimeout(() => {

    const data = { id: 1, name: "Database Record" };

    callback(data); // The callback is executed once the data is 'ready'

  }, 2000);

}



function processData(result) {

  console.log("Data received: ", result.name);

}



fetchData(processData);

The Structural Anatomy of a Callback​

When defining a function that accepts a callback, you are essentially defining a "contract." The primary function handles the complex logic (like timing or requests), and the callback handles the specific result.

Anonymous Callbacks​

While named functions improve readability, developers frequently use anonymous arrow functions as callbacks for shorter, one-time tasks.


setTimeout(() => {

  console.log("Three seconds have passed.");

}, 3000);

The Challenge: Callback Hell​

As applications grow in complexity, asynchronous tasks often depend on the results of previous asynchronous tasks. This leads to nesting multiple callbacks within one another.

When you have a sequence of five or six asynchronous operations that must happen in order, your code begins to grow horizontally rather than vertically. This phenomenon is known as Callback Hell or the Pyramid of Doom.

Identifying the Pyramid of Doom​


getUser(1, (user) => {

  getProfile(user.profileId, (profile) => {

    getPosts(profile.id, (posts) => {

      getComments(posts[0].id, (comments) => {

        console.log("Finally reached the comments: ", comments);

        // The code continues to indent further and further...

      });

    });

  });

});

Problems Caused by Callback Hell​

Technical Standards and Best Practices​

To mitigate the issues associated with callbacks in a professional environment, follow these structural rules:

While callbacks remain a core part of the language's history and are still used for simple events, modern JavaScript development primarily utilizes Promises and Async/Await to solve the structural failures of callback-heavy architectures.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Event Loop

Next

Promises