Callback in JavaScript
🧠 What Is a Callback?
A callback is a function passed as an argument to another function and executed later. It allows asynchronous and event-driven programming in JavaScript.
>>“Callbacks give functions the power to hand over control to another function.”
🔧 Basic Syntax
Simple Callback Example
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Alice", sayBye);
// Hello, Alice
// Goodbye!🎯 Callback with Anonymous Function
Instead of naming the callback function, you can define it inline.
Anonymous Callback
greet("Bob", function () {
console.log("See you!");
});
// Hello, Bob
// See you!⚙️ Why Use Callbacks?
- To run code after a task completes (like a network request)
- To provide flexible logic to functions
- To handle asynchronous operations
⏱️ Callbacks in Asynchronous Code
Callbacks are heavily used with timers and asynchronous tasks like API calls.
Async Callback with setTimeout
console.log("Start");
setTimeout(() => {
console.log("Delayed Message");
}, 1000);
console.log("End");
// Output:
// Start
// End
// Delayed Message (after 1s)📚 Real-World Example: Simulated API Call
Simulated Async Operation
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: "Item" };
callback(data);
}, 1500);
}
fetchData(function (data) {
console.log("Received:", data);
});😖 Callback Hell
Nesting many callbacks can lead to complex, hard-to-read code, known as callback hell.
⚠️ Callback Hell Example
doTask1(() => {
doTask2(() => {
doTask3(() => {
console.log("All tasks done");
});
});
});Note
💡 Modern JavaScript prefers Promises or async/await to avoid callback hell.
🆚 Callback vs Promise
- Callback: More flexible, but can become messy
- Promise: Cleaner syntax and better error handling
🔗 Further Reading
>>“Callbacks are the backbone of asynchronous JavaScript. Learn them well, and the rest becomes easier.”