Callbacks in JavaScript
A callback is a function that is passed as an argument to another function and is executed later, usually after an asynchronous operation has finished.
Callbacks are one of the fundamental ways to handle asynchronous behavior in JavaScript — for example, waiting for a timer, network request, or file to finish loading.
How Callbacks Work
JavaScript executes code synchronously (line by line).
If you perform a time-consuming operation (like fetching data from a server), it could block other code.
To prevent this, JavaScript uses callbacks to defer execution of certain code until a task is completed.
Example: Simple Callback
function greet(name, callback) {
console.log("Hello " + name);
callback(); // Executed after greeting
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Alice", sayGoodbye);
Example: Asynchronous Callback (setTimeout)
console.log("Start");
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
console.log("End");
Callback Hell
When callbacks are nested inside each other, the code becomes hard to read and maintain — this is called callback hell or pyramid of doom.
Example:
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);
Avoiding Callback Hell
Callback hell can be avoided by using:
- Named functions instead of anonymous callbacks.
- Promises and Async/Await, which make code more readable and maintainable.
Example using Promises:
fetch("<https://api.example.com/data>")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Summary Table
Concept | Description | Example |
---|---|---|
Callback | Function passed as an argument and executed later | setTimeout(() => {...}, 1000) |
Synchronous Callback | Runs immediately | arr.forEach(cb) |
Asynchronous Callback | Runs after a delay or async task | setTimeout(cb, 1000) |
Callback Hell | Nested callbacks that reduce readability | Multiple setTimeout calls |
Modern Alternatives | Promises, Async/Await | Cleaner async handling |