A callback is a function passed as an argument to another function, and it is executed after some operation is completed.
🔹 Key Characteristics:
- Used to handle asynchronous operations like API calls, file reading, or timers.
- The parent function calls back the function once the task is done.
- Helps in function composition and code modularity.
✅ Example:
function greetUser(name, callback) {
console.log("Hi, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greetUser("Teekam", sayBye);
Output:
Hi, Teekam
Goodbye!
✅ Common Usage in Asynchronous Code:
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
🔸 Callback Hell (Nested Callbacks):
When callbacks are nested inside each other too deeply, it leads to messy, hard-to-read code.
doSomething(() => {
doNext(() => {
doAnother(() => {
console.log("Callback hell!");
});
});
});
📝 In Summary:
A callback is a function passed into another function to be executed later, often after an asynchronous task completes. It enables non-blocking code, but excessive use can lead to callback hell, which is often solved by promises or async/await.