JavaScript Callbacks
14 April 2025 | Category: JavaScript
A callback is a function passed as an argument to another function. It allows you to run code after something else has finished executing, making JavaScript highly flexible and asynchronous.
đź§ What is a Callback?
In simple terms:
A callback is a function that is passed to another function and is executed later, often after an operation completes.
âś… Basic Syntax
function greeting(name) {
console.log('Hello, ' + name);
}
function processUserInput(callback) {
const name = 'Alice';
callback(name);
}
processUserInput(greeting); // Output: Hello, Alice
greeting
is the callback function.- It is passed to
processUserInput
and called inside that function.
🕰️ Why Use Callbacks?
JavaScript is asynchronous. Callbacks let us handle tasks like:
- API requests
- File reading
- User interactions
- Timers
Example with setTimeout
:
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
🎯 Custom Example: Callbacks for Tasks
function doHomework(subject, callback) {
console.log(`Starting my ${subject} homework.`);
callback();
}
function finished() {
console.log('I have finished my homework!');
}
doHomework('math', finished);
// Output:
// Starting my math homework.
// I have finished my homework!
🔄 Synchronous vs Asynchronous Callbacks
Synchronous Callback:
Runs immediately during function execution.
function logMessage(callback) {
console.log('Before callback');
callback();
console.log('After callback');
}
logMessage(() => {
console.log('Inside callback');
});
Asynchronous Callback:
Runs later, after an async operation finishes.
function fetchData(callback) {
setTimeout(() => {
console.log('Data fetched');
callback();
}, 1000);
}
fetchData(() => {
console.log('Callback after fetch');
});
⚠️ Callback Hell
When callbacks are nested too deeply, it becomes hard to read and maintain:
login(user, () => {
getProfile(user, () => {
updateSettings(user, () => {
console.log("All done!");
});
});
});
➡ This is called Callback Hell or the Pyramid of Doom.
âś… Solution: Use Promises or async/await for better flow control.
🔚 Summary
Concept | Description |
---|---|
Callback | A function passed to another function |
Use case | Async operations like API calls, timers |
Common issue | Callback Hell (deep nesting) |
Modern solution | Promises & async/await |