What is a Callback?
A callback is a function passed into another function as an argument, then executed inside the outer function. Callbacks are essential for asynchronous programming in JavaScript.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function afterGreet() {
console.log("Callback executed!");
}
greet("Alice", afterGreet);
Try it Yourself →
Async with Callbacks
Callbacks shine with async operations like timers or file reads. Here's a simulated async task using setTimeout:
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: "Item" };
callback(data);
}, 1000);
}
fetchData((result) => {
console.log("Data received:", result);
});
Try it Yourself →
Callback Hell
Nesting too many callbacks creates "callback hell" — hard-to-read pyramid code. Promises solve this.
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 500);
}, 500);
}, 500);
Try it Yourself →