Callbacks
This lesson explains Callbacks in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.
JavaScript Callbacks Overview
A JavaScript callback is a function passed as an argument to another
function and executed later. Callbacks are used to control when code runs,
especially after events, timers, array operations, API calls, and
asynchronous tasks.
Callback functions are one of the foundations of asynchronous JavaScript.
They are commonly used with addEventListener(),
setTimeout(), setInterval(), array methods,
custom utility functions, and older Node.js APIs.
| Callback Concept | Description | Common Usage |
| Callback Function | A function passed to another function. | Events, timers, array methods. |
| Synchronous Callback | Runs immediately during execution. | map, filter, forEach. |
| Asynchronous Callback | Runs later after a task completes. | setTimeout, API calls, events. |
| Higher-Order Function | A function that accepts or returns another function. | Reusable utilities. |
| Error-First Callback | Callback pattern where error is the first argument. | Legacy Node.js APIs. |
JavaScript Callback Example
function greetUser(name, callback) {
const message = "Hello " + name;
callback(message);
}
function showMessage(text) {
console.log(text);
}
greetUser("John", showMessage);
setTimeout(function() {
console.log("This message runs later");
}, 1000);
In this example, showMessage is passed as a callback to
greetUser. The setTimeout() example shows an
asynchronous callback that runs after a delay.
Top 10 JavaScript Callback Examples
The following examples show common callback patterns used in frontend,
backend, asynchronous programming, array processing, and event handling.
| # | Example | Syntax |
| 1 | Custom Callback | function run(callback) { callback(); } |
| 2 | Callback with Argument | function greet(name, callback) { callback(name); } |
| 3 | setTimeout Callback | setTimeout(function() { console.log("Done"); }, 1000); |
| 4 | setInterval Callback | setInterval(function() { console.log("Tick"); }, 1000); |
| 5 | Click Event Callback | button.addEventListener("click", function() { console.log("Clicked"); }); |
| 6 | forEach Callback | items.forEach(function(item) { console.log(item); }); |
| 7 | map Callback | numbers.map(function(number) { return number * 2; }); |
| 8 | filter Callback | users.filter(function(user) { return user.active; }); |
| 9 | reduce Callback | prices.reduce(function(total, price) { return total + price; }, 0); |
| 10 | Error-First Callback | function done(error, data) { if (error) { return; } console.log(data); } |
Popular Real-World JavaScript Callback Examples
These examples show how callbacks are used in real projects for user
interactions, data processing, timers, validation, and asynchronous flows.
| Scenario | Callback Pattern |
| Button Click Handler | button.addEventListener("click", handleClick); |
| Form Submit Handler | form.addEventListener("submit", handleSubmit); |
| Live Search Input | searchInput.addEventListener("input", handleSearch); |
| Delay Notification | setTimeout(showNotification, 3000); |
| Auto Refresh Dashboard | setInterval(refreshDashboard, 60000); |
| Render List Items | items.forEach(renderItem); |
| Transform API Data | users.map(formatUser); |
| Filter Active Records | users.filter(isActiveUser); |
| Calculate Cart Total | cartItems.reduce(calculateTotal, 0); |
| Legacy Node.js API | readFile("data.txt", function(error, data) { console.log(data); }); |
Best Practices
- Use descriptive callback names for better readability.
- Keep callback functions small and focused.
- Use named functions when the callback logic is reused.
- Use arrow functions for short callbacks when appropriate.
- Avoid deeply nested callbacks to prevent callback hell.
- Use promises or async/await for complex asynchronous flows.
- Always handle errors in asynchronous callbacks.
- Remove event callbacks when they are no longer needed.
Common Mistakes
- Calling the callback immediately instead of passing the function reference.
- Forgetting to pass required arguments to the callback.
- Creating deeply nested callbacks that are hard to maintain.
- Not handling errors in asynchronous callbacks.
- Using callbacks when promises or async/await would be clearer.
- Writing large anonymous callback functions inside another function.
- Adding duplicate event callbacks accidentally.
Key Takeaways
- A callback is a function passed as an argument to another function.
- Callbacks can run immediately or later after an asynchronous task.
- They are commonly used in events, timers, and array methods.
- Callbacks help create reusable and flexible JavaScript functions.
- Deeply nested callbacks can make code difficult to maintain.
- Promises and async/await are often better for complex async workflows.
Pro Tip
Use callbacks for simple events, timers, and array methods. When callback
logic becomes nested or difficult to read, refactor the code using promises
or async/await.