Javascript
Callback
Introduction
In JavaScript a callback is just a function that is passed into another function so that it runs after something finishes.
Basic Example
- Here
secondTaskis a callback because it runs afterfirstTaskfinishes
Callback Hell
Callback hell happens when you have many callbacks inside callbacks where each callback depends on the one before it.
Example of Callback Hell
Problems with Callback Hell
- The code looks ugly and hard to read
- It is hard to handle errors
- It is difficult to maintain or add new features
- Creates a "pyramid of doom" structure
How to Fix Callback Hell
- Promises - Promises make code look cleaner and more manageable
- Async/Await - Modern syntax that makes asynchronous code look synchronous
Important Notes
- Callbacks are fundamental to JavaScript's asynchronous nature
- They allow code to continue running while waiting for operations to complete
- Modern JavaScript prefers Promises and async/await over nested callbacks
- Callbacks are still widely used in event handlers and array methods like
map(),filter(),forEach()