Callback function
- A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
- Callback functions are used to achieve asynchronous behaviour in JavaScript
Drawback of using the Callback function
There are two drawbacks of using the callback function - The diamond problem or callback hell
- Inversion of Control
The diamond problem / callback hell
- When we have multiple callbacks nested inside each other then it is called a callback hell
- Because of this debugging and maintaining the code becomes difficult.
- It is called a diamond or pyramid problem because nested callbacks look that way
Example :
Inversion of Control / Trust issues with callback
- Sometimes callback functions do not behave the way they should.
- One classic example is :
assume we have a set timeout function which has a timer of 10 sec
But in the global space we have written so many lines that the time taken to execute those statements is more than 10 sec then as a result the event loop will never find the call stack empty and hence, even after a long time the set timeout has expired the callback function passed inside it will never get executed the way we wanted it to get executed