Callback hell
Learn the pyramid of nested callbacks and why it is problematic.
Callback hell
When the result of one asynchronous operation feeds into another, nesting callbacks is natural. But as the number of steps grows, the code drifts to the right and becomes unreadable. This pattern is called callback hell or the pyramid of doom.
loadUser(id, (err, user) => {
loadPosts(user, (err, posts) => {
loadComments(posts, (err, comments) => {
// each level indents further
});
});
});As the pyramid deepens, error handling, return values, and flow control all become harder.
Why is it a problem?
Callback hell is not just an aesthetic issue; it has real costs. Error handling must be repeated at every level, and a return in one level does not affect the others. When loops and conditionals nest together, following the flow becomes hard.
Besides, variable names clash in nested callbacks: you end up writing err and result at every level. Changing or debugging the code is also harder. The next lesson shows how to fix this pattern.
Exercise Write two nested setTimeout calls
Write two nested setTimeout calls. The outer timer starts the inner timer after 200 ms. The inner timer prints a short message with console.log after another 200 ms. The inner setTimeout must be inside the outer timer's callback.
Show example solution
setTimeout(() => {
setTimeout(() => {
console.log('Done');
}, 200);
}, 200);
Test yourself
-
Which is a symptom of callback hell?
- A flat, short function chain
- Nested, right-drifting callbacks
- A single synchronous function
- Using promises
Show answer
Nested, right-drifting callbacks — Correct! Nested callbacks drift to the right and become unreadable.
-
Complete the nested callback
loadUser(id, (err, user) => { loadPosts(user, ____ => { loadComments(posts, (err, comments) => {}); }); });Show answer
loadUser(id, (err, user) => { loadPosts(user, (err, posts) => { loadComments(posts, (err, comments) => {}); }); }); -
Match the concepts
- callback hell
- Nested callbacks
- pyramid of doom
- Indent drift
- nested callback
- Deep level
- return
- Early exit
-
What is the main problem with callback hell?
- It runs too fast
- It consumes too much memory
- Browsers do not support it
- It is hard to read and maintain
Show answer
It is hard to read and maintain — Correct! The nested structure makes readability and maintenance difficult.