🔁 JavaScript Callbacks
Last Updated: 27th October 2025
Callbacks?
A callback is a function passed as an argument to another function, which is executed later (after some operation completes). It helps manage tasks that take time, like file reading, API requests, or timers.
Hinglish Tip 🗣: Callback ek “helper function” hai jo tab call hota hai jab doosra kaam poora ho jaata hai — jaise “kaam hone ke baad mujhe bula lena!”
✏ Example: Basic Callback
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Riya", sayBye);
Here, sayBye() is passed as a callback and executed after greet() finishes.
⚙️ Synchronous vs Asynchronous Callbacks
- Synchronous Callbacks:
- Runs immediately within the same function (blocking)
- Asynchronous Callbacks:
- Runs later after a delay or async event
// Synchronous Callback
function calculate(a, b, callback) {
let result = a + b;
callback(result);
}
calculate(4, 6, function (res) {
console.log("Result:", res);
});
🗣 Hinglish: Yahaan callback turant chala — bina wait kiye. So Output is
10.
// Asynchronous Callback
console.log("Start");
setTimeout(() => {
console.log("Async task completed!");
}, 2000);
console.log("End");
🗣 Hinglish: Yahaan callback 2 second baad chala — kyunki setTimeout() asynchronous hai.So Output is
Start ,End,Async task completed!.
⚠️ Callback Hell (Nested Callbacks)
When multiple async callbacks are nested, code becomes hard to read and maintain — this is called Callback Hell.
setTimeout(() => {
console.log(" Task 1 Done");
setTimeout(() => {
console.log(" Task 2 Done");
setTimeout(() => {
console.log(" Task 3 Done");
}, 1000);
}, 1000);
}, 1000);
Deep nesting → hard to debug and scale.Use Promises or Async/Await to handle async operations cleanly.