Skip to main content

Command Palette

Search for a command to run...

Callbacks in JavaScript: Why They Exist

Updated
•2 min read•View as Markdown

What a Callback Function Is
A callback function is a function that is passed as an argument to another function and is executed later.

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

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

greet("John", sayBye);

Here, sayBye is passed as a callback and executed after the greeting.


Why Callbacks Are Used in Asynchronous Programming

JavaScript is asynchronous, meaning some operations (like API calls or timers) take time to complete. Callbacks allow us to run code after these operations finish.

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

The function passed to setTimeout is a callback that runs later.


Passing Functions as Arguments

Functions in JavaScript are first-class citizens, which means they can be passed just like variables.

function process(callback) {
  callback();
}

process(() => {
  console.log("Callback executed");
});

Callback Usage in Common Scenarios

Callbacks are commonly used in:

  • Timers (setTimeout, setInterval)

  • Event listeners

document.addEventListener("click", () => {
  console.log("Clicked!");
});
  • API calls (handling responses after data is fetched)

Basic Problem of Callback Nesting

When multiple asynchronous operations depend on each other, callbacks can get deeply nested, making the code hard to read and maintain, this is known as callback hell.

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

This nested structure becomes difficult to manage and debug.