Back to course

Callbacks and the Dreaded Callback Hell

JavaScript: The Complete '0 to Hero' Beginner Course

95. Callbacks and Callback Hell

A callback function is a function passed as an argument to another function, which is then executed later, once a task is complete.

Example: Basic Callback

javascript function loadData(callback) { // Simulate fetching data after 2 seconds setTimeout(() => { const data = { content: 'Loaded text' }; callback(data); // Execute the callback when done }, 2000); }

loadData((result) => { console.log('Finished loading:', result.content); }); console.log('This runs first!'); // Non-blocking

Callback Hell (The Pyramid of Doom)

When we have multiple asynchronous operations that depend on the results of the previous one, nesting callbacks deeply results in code that is hard to read, maintain, and debug.

javascript getData(function(data) { parseData(data, function(parsed) { validate(parsed, function(validated) { saveToDB(validated, function(success) { // ... 5 more levels deep }); }); }); });

This led to the invention of Promises.