SyntaxStudy
Sign Up
JavaScript Beginner 7 min read

Callback Functions

Callback Functions

A callback is a function passed as an argument to another function, to be invoked later — either after a time delay, after an event, or after an asynchronous operation completes. Callbacks were the original mechanism for handling async operations in JavaScript before promises were introduced.

Simple Callbacks

Higher-order functions like Array.map(), setTimeout(), and event listeners all accept callbacks. These are synchronous or asynchronous depending on the function that calls them.

Error-First Callbacks (Node.js Convention)

Node.js established a convention for async callbacks: the first argument is always an error (or null if no error), and subsequent arguments carry the successful result. This forces callers to handle errors explicitly.

Callback Hell

When callbacks are nested inside callbacks, code can become deeply indented and hard to follow — nicknamed "callback hell" or the "pyramid of doom." Promises and async/await were introduced to solve this readability problem.

Example
function fetchUser(id, callback) {
  setTimeout(function() {
    if (id > 0) {
      callback(null, { id: id, name: 'User ' + id });
    } else {
      callback(new Error('Invalid ID'), null);
    }
  }, 100);
}
fetchUser(1, function(err, user) {
  if (err) {
    console.error(err.message);
    return;
  }
  console.log(user.name);
});
fetchUser(0, function(err, user) {
  if (err) console.error(err.message); // Invalid ID
});
[1, 2, 3].forEach(function(n) {
  console.log(n * 2); // synchronous callback
});
Pro Tip

Always handle errors in callbacks — an uncaught error in a callback will silently fail in many environments. Modern code should prefer promises, but understanding callbacks is essential for reading older codebases and libraries.