Imagine you are at a busy restaurant. You place your order, but instead of standing at the counter waiting for your food, the waiter gives you a buzzer. You go sit down, chat with friends, or check your phone. When the food is ready, the buzzer goes off.
In JavaScript, a Callback Function is exactly like that buzzer.
1. What is a Callback Function?
In simple terms, a callback is a function passed as an argument to another function.
2. Why do we use it?
JavaScript usually runs code line-by-line. But some things (like loading a large image or fetching data) take time. Callbacks prevent the whole website from "freezing" while waiting for that task to finish.
3. A Simple Example
Let’s look at a basic example where we pass a greeting function into another function.
// The Callback Function
function sayGoodbye() {
console.log("Goodbye! Task is finished.");
}
// The Main Function
function processUser(callback) {
console.log("Processing user data...");
// Simulating a task, then calling the callback
callback();
}
// Passing sayGoodbye as an argument
processUser(sayGoodbye);
output
- Chef is cooking...
- Your food is ready
What happened here?
-
processUserstarts running. - It prints "Processing user data..."
- It then executes
callback(), which is actually thesayGoodbyefunction we passed in.
4. Practical Use: setTimeout
The most common way beginners see callbacks is with timers.
console.log("Start");
setTimeout(function() {
console.log("This happens after 3 seconds!");
}, 3000);
console.log("End");
The Result:
- "Start" is printed.
- "End" is printed.
- 3 seconds later, the callback function inside setTimeout runs and prints "This happens after 3 seconds!"
Here, the anonymous function inside is the callback. It waits for the 3-second "long task" to finish before running.
5. 3 Golden Rules
- A callback is just a function.
-
Pass the name, don't call it: Pass
myFunc, notmyFunc(). - Async Power: They are the secret behind why websites can do many things at once.

Top comments (0)