Callbacks0%

Callbacks

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Callbacks in Modern JavaScript

JavaScript is a single-threaded runtime environment driven by a non-blocking Event Loop. In order to perform long-running tasks (such as network requests, timer delays, or file I/O) without freezing the user interface, JavaScript relies on asynchronous callbacks.


1. What is a Callback Function?

A callback is simply a function passed into another function as an argument, intended to be executed ("called back") at a designated time or after an asynchronous operation completes.

Synchronous vs. Asynchronous Callbacks

JavaScript
// 1. Synchronous Callback: Executes immediately during caller execution
const numbers = [1, 2, 3];
numbers.forEach((num) => console.log(`Sync: ${num}`));
 
// 2. Asynchronous Callback: Defers execution until an event completes
console.log('Task A: Start timer');
setTimeout(() => {
console.log('Task B: Timer callback executed after 1000ms');
}, 1000);
console.log('Task C: Script continues uninterrupted');

Execution Output Order:

  1. 1
    Task A: Start timer
  2. 2
    Task C: Script continues uninterrupted
  3. 3
    Task B: Timer callback executed after 1000ms

2. The JavaScript Event Loop & Callback Queue

How does JavaScript manage asynchronous callbacks with only a single thread?

Output
┌──────────────────────────────────────────────────────────┐
│ CALL STACK (Single Thread) │
│ console.log('A') ──► setTimeout(...) ──► console.log('C')│
└─────────────────────────────┬────────────────────────────┘
│ Registers Web API Timer
▼
┌──────────────────────────────────────────────────────────┐
│ WEB APIs (Browser Background Engine) │
│ Timer countdown (1000ms) │
└─────────────────────────────┬────────────────────────────┘
│ Timer expires
▼
┌──────────────────────────────────────────────────────────┐
│ CALLBACK / TASK QUEUE (FIFO) │
│ [ () => console.log('B') ] │
└─────────────────────────────┬────────────────────────────┘
│ Event Loop pushes when Call Stack is empty!
▼
[ Executes Callback ]
  1. 1
    Functions execute on the Call Stack.
  2. 2
    Asynchronous operations (setTimeout, fetch) are delegated to browser Web APIs.
  3. 3
    Upon completion, the callback is placed into the Callback Queue (Task Queue).
  4. 4
    The Event Loop constantly monitors the Call Stack. When the Call Stack is empty, it pushes the queued callback onto the stack.

3. The Classic Problem: "Callback Hell" (Pyramid of Doom)

When multiple dependent asynchronous operations must execute sequentially, nesting callbacks leads to unmaintainable, deeply indented code:

JavaScript
// ANTI-PATTERN: Callback Hell
getUser(userId, (err, user) => {
if (err) return handleError(err);
getOrders(user.id, (err, orders) => {
if (err) return handleError(err);
getOrderDetails(orders[0].id, (err, details) => {
if (err) return handleError(err);
processPayment(details.amount, (err, receipt) => {
if (err) return handleError(err);
console.log('Transaction finalized:', receipt);
});
});
});
});

Pitfalls of Callback Hell:

  • Deeply nested indentation ("Pyramid of Doom").
  • Repetitive, scattered error handling in every callback.
  • High cognitive load and severe difficulty tracking control flow.
  • Lack of native return values or composite operations.

4. Modern Solution: Evolution to Promises

To solve Callback Hell, ES6 introduced Promises, which flatten nested callbacks into linear chains (.then().catch()), later elevated by ES2017 async/await.


Interactive Quiz

Practice Quiz

Question 1
What is a callback function in JavaScript?
Question 2
What is the primary role of the JavaScript Event Loop?
Question 3
What is "Callback Hell"?
Question 4
In what order will console.log('1'), setTimeout(() => console.log('2'), 0), and console.log('3') print?
Question 5
What standard Node.js convention was historically used for callback arguments?
Next Lesson

Promises Basics

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext