JavaScript Callbacks
A callback function is a function passed as an argument to another function and is executed after the completion of that function. Callbacks enable asynchronous programming in JavaScript.
Key Topics
Callback Basics
A callback is simply a function that is passed as an argument to another function to be executed later.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function afterGreeting() {
console.log("This is a callback function.");
}
greet("Alice", afterGreeting);
Output
> Hello, Alice
> This is a callback function.
Explanation: The greet
function takes another function, afterGreeting
, as a callback and invokes it after logging a greeting message.
Using Callbacks
Callbacks are widely used in asynchronous operations like file reading or network requests.
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched successfully!");
}, 2000);
}
fetchData((message) => {
console.log(message);
});
Output
> Data fetched successfully!
Explanation: The fetchData
function simulates an asynchronous operation with setTimeout
and invokes the callback function with the result after 2 seconds.
Error Handling in Callbacks
Callbacks can also handle errors by passing error objects or messages as the first argument.
function processData(callback) {
setTimeout(() => {
const error = false;
if (error) {
callback("An error occurred.", null);
} else {
callback(null, "Processing complete.");
}
}, 1000);
}
processData((err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
Output
> Processing complete.
Explanation: The processData
function handles errors by passing them as the first argument to the callback, allowing the caller to respond accordingly.
JavaScript Usage in DOM
Below is a complete DOM example where a callback is used to dynamically update content after a simulated asynchronous operation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Callbacks in DOM</title>
</head>
<body>
<button onclick="updateMessage()">Fetch Message</button>
<p id="output"></p>
<script>
function fetchMessage(callback) {
setTimeout(() => {
callback("Hello from callback!");
}, 1500);
}
function updateMessage() {
fetchMessage((message) => {
document.getElementById("output").textContent = message;
});
}
</script>
</body>
</html>
Key Takeaways
- Callback Basics: Pass functions as arguments to execute them later.
- Asynchronous Operations: Use callbacks to handle delayed responses like data fetching.
- Error Handling: Pass error objects in callbacks to signal issues.
- DOM Integration: Use callbacks to update the UI dynamically after asynchronous tasks.