call back
🔹 What is a Callback?
A callback is simply a function passed as an argument to another function, so that it can be executed later (or “called back”) once some task is done.
👉 In short: A function inside another function.
🔹 Simple Example
function greet(name, callback) {
console.log("Hello, " + name);
callback(); // call the callback function
}
function sayBye() {
console.log("Goodbye!");
}
greet("Amit", sayBye);
Output:
Hello, Amit
Goodbye!
Here:
sayByeis passed as a callback togreet.After greeting,
greetexecutes the callback.
🔹 Anonymous Callback
Instead of defining a separate function, you can pass an anonymous function:
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
greet("Amit", function() {
console.log("Goodbye!");
});
🔹 Callbacks with setTimeout
Callbacks are very common in asynchronous JavaScript:
console.log("Start");
setTimeout(function() {
console.log("Callback executed after 2 seconds");
}, 2000);
console.log("End");
Output:
Start
End
Callback executed after 2 seconds
👉 Notice how setTimeout doesn’t block the program. The callback runs later.
🔹 Callback Example with Data
function getUser(id, callback) {
setTimeout(() => {
console.log("Fetched user from database");
callback({ id: id, name: "Amit" });
}, 1000);
}
getUser(101, function(user) {
console.log("User received:", user);
});
🔹 The Problem: Callback Hell 😵
When many callbacks are nested, code becomes messy:
getUser(101, function(user) {
getPosts(user.id, function(posts) {
getComments(posts[0].id, function(comments) {
console.log(comments);
});
});
});
This is called callback hell → solved by Promises and async/await.
✅ So, in summary:
Callback = function passed as argument.
Useful for async tasks (e.g., reading files, DB calls, API requests).
But too many nested callbacks → callback hell → solved by Promises/async-await.