Common Callback Use Cases
You'll learn where callbacks show up most often in real JavaScript code and why they're indispensable.
Why Callbacks Are Everywhere
Callbacks aren't just a theoretical pattern—they're the backbone of JavaScript's asynchronous model. Understanding the most common use cases helps you recognize the pattern and use it confidently.
The Four Main Callback Scenarios
Event Handlers
User interactions like clicks, keypresses, and form submissions all use callbacks. The browser calls your function when the event happens:
button.addEventListener('click', function() {
console.log('Button was clicked!');
});
Timers
setTimeout and setInterval execute your callback after a delay or repeatedly:
setTimeout(function() {
console.log('This runs after 1 second');
}, 1000);
Array Methods
Methods like forEach, map, filter, and reduce call your function for each element:
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num * 2);
});
I/O Operations
Reading files, making network requests, or querying databases—anything that takes time uses callbacks to notify you when complete:
// Conceptual example (not runnable yet)
readFile('data.txt', function(error, contents) {
if (error) {
console.error('Failed to read file');
} else {
console.log(contents);
}
});
The Pattern
Notice the pattern: you provide a function, and JavaScript calls it later when something happens—an event fires, time elapses, iteration occurs, or data arrives. You don't call these functions yourself; you hand them off.
Key Takeaway: Event handlers, timers, array methods, and I/O operations all rely on callbacks because they represent "do this when ready" scenarios where the timing isn't immediate or predictable.