Callbacks
Before promises and async/await became popular, JavaScript handled asynchronous behavior mainly using callbacks.
Even today, callbacks are everywhere in JavaScript, especially in event handling and browser APIs.
What Is a Callback?
A callback is a function that is passed as an argument to another function and executed later.
In simple terms:
- You give a function to another function
- That function decides when to call it
A Simple Callback Example
function greet(name, callback) {
callback("Hello " + name);
}
greet("Alex", function(message) {
console.log(message);
});
Here, the second function is the callback.
Why Callbacks Exist
JavaScript is single-threaded, meaning it can only do one thing at a time.
Callbacks allow JavaScript to:
- Handle time-consuming tasks
- Respond after an operation completes
- Keep applications responsive
Callbacks in Asynchronous Code
Callbacks are often used with timers and events.
setTimeout(function() {
console.log("Executed after delay");
}, 1000);
The callback runs after the delay finishes.
Callbacks in Event Handling
Browser events rely heavily on callbacks.
button.addEventListener("click", function() {
console.log("Button clicked");
});
The function runs only when the event occurs.
Callback Hell
When callbacks are deeply nested, code becomes hard to read and maintain.
doTask(function() {
doAnotherTask(function() {
doMoreWork(function() {
console.log("Done");
});
});
});
This problem is known as callback hell.
How JavaScript Evolved
To solve callback hell, JavaScript introduced:
- Promises
- Async / Await
Callbacks still exist, but modern code prefers cleaner alternatives.
When Callbacks Are Still Useful
- Event listeners
- Simple async tasks
- Legacy codebases
Understanding callbacks helps you read older and modern JavaScript code alike.
Common Beginner Mistakes
- Calling a callback immediately instead of passing it
- Forgetting error handling
- Creating deeply nested callbacks
Callbacks should stay simple.
Thumb Rules
- A callback is just a function
- It is executed later by another function
- Avoid deep nesting
- Prefer promises for complex flows
What Comes Next?
Now that you understand callbacks, the next step is learning how JavaScript manages asynchronous tasks internally.
In the next lesson, we will explore the event loop.