What is a Callback?
A callback is a function passed into another function, to be called later when something happens or a task is finished.
Analogy:
Imagine you order food and give the restaurant your phone number so they can call you when your food is ready. Your phone number is the callback.
Why Are Callbacks Important?
JavaScript is single-threaded and often needs to wait for things (like loading data or waiting for a user action).
Instead of stopping everything, it uses callbacks to say, “Do this later, when the waiting is done.”
How Do Callbacks Work?
1. Writing a Function That Accepts a Callback
function doSomethingLater(callback) {
console.log("Doing something...");
callback();
}
2. Defining the Callback Function
function sayHello() {
console.log("Hello, I'm the callback!");
}
3. Passing the Callback
doSomethingLater(sayHello);
Output:
Doing something...
Hello, I'm the callback!
4. Using Inline (Anonymous) Callbacks
doSomethingLater(function() {
console.log("This is an inline callback!");
});
Real-Life Applications
setTimeout and setInterval
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
Event Listeners
button.addEventListener('click', function() {
console.log("Button clicked!");
});
Fetching Data (with Promises, but still uses callbacks)
fetch('https://api.example.com/data')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
Common Misconceptions
Callbacks are not always asynchronous.
Some callbacks are called right away.Callbacks are just functions.
There’s nothing special about them except how they’re used.
Callback Cheat Sheet
Definition:
A callback is a function you pass to another function to be called later.
Basic Example:
function callback() { ... }
someFunction(callback);
Anonymous Example:
someFunction(function() { ... });
Typical Uses:
setTimeout, setInterval
Event handling (like clicks)
Fetching data from APIs
Key Point:
Callbacks help JavaScript handle tasks that take time, so your code can keep running without waiting.