Callbacks
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
Execution Output Order:
- 1
Task A: Start timer - 2
Task C: Script continues uninterrupted - 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?
- 1Functions execute on the Call Stack.
- 2Asynchronous operations (
setTimeout,fetch) are delegated to browser Web APIs. - 3Upon completion, the callback is placed into the Callback Queue (Task Queue).
- 4The 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:
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.
Practice Quiz
Promises Basics
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Object Destructuring in Depth | Promises Basics |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.