Javascript
Callback
Learn JavaScript callbacks - functions passed as arguments, callback hell problems, and how to write clean asynchronous code with callbacks
Introduction
In JavaScript a callback is just a function that is passed into another function so that it runs after something finishes.
Basic Example
function firstTask(callback) {
console.log("First task done")
callback()
}
function secondTask() {
console.log("Second task done")
}
firstTask(secondTask)- 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
doSomething(function(result1) {
doSomethingElse(result1, function(result2) {
doThirdThing(result2, function(result3) {
doFourthThing(result3, function(result4) {
console.log("All done")
})
})
})
})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()
Hoisting
Master JavaScript hoisting - how variable and function declarations are moved to the top, differences between var/let/const, and the Temporal Dead Zone
Promise
Master JavaScript Promises - understand promise states, then/catch/finally methods, promise chaining, microtask queue, and solving callback hell