Callbacks in JavaScript: Pros, Cons, and How to Tame Them
2 min readMay 2, 2025
Callback function:
- A callback is a function that is passed as an argument to another function that executes the callback based on the result. They are basically functions that are executed only after a result is produced.
- Callbacks help us develop asynchronous JavaScript code.
- Callbacks make sure that a function won’t run before a prerequisite task is completed.
In this example, message is an example of a callback function.
When called, it writes, “This message is shown after 3 seconds” to the console.
There is a built-in method in JavaScript called “setTimeout”, which waits a specified time in milliseconds before performing an action.
Usage of Callback function:
- Usually async callbacks are used for accessing values from databases, downloading images, reading files, and so on.
- Callback functions wait for a response, and when the response is sent, then they execute.
Problems with callback function:
- Callback hell : It refers to nested callback functions.
- Inversion of control( IoC ): When using third-party code you often have inversion of control issues where you cannot trust the third-party code.
Callback hell:
- Callback hell happens when you write a function, and inside it, you call another function using a callback, and then inside that callback, you call another one, and so on.
- This creates a chain of nested functions that grow sideways (like a triangle), making the code look messy, hard to read, and difficult to manage.
Example:
doTask1(() => {
doTask2(() => {
doTask3(() => {
doTask4(() => {
console.log("All tasks done");
});
});
});
});
It becomes a “pyramid of doom”.
Inversion of Control:
- You pass your logic (callback) to someone else’s function, trusting it will be called properly but you lose control over when and how it’s called.
Note:
Ways to mitigate callback problems:
- writing comments
- Split functions into smaller functions
- Use promises
- Use async/await