Callback
A callback is a callback mechanism where a function or action is passed as an argument to another function and executed later—at the appropriate moment. Callbacks are widely used in programming, web development, event handling, APIs, and asynchronous operations.
What is a callback?
A callback (or callback function) is a function passed to another function so that it can be called later, after a specific action has been completed.
The main idea: you provide “what needs to be done” in advance, and the system will execute it when the relevant event occurs.
Example:
After sending a request to a server, the callback function will execute once the response arrives.
Why are callbacks needed?
Callbacks allow you to:
- Control the sequence of operations
- Handle the results of asynchronous actions
- Respond to events (clicks, page loads, errors)
- Create flexible and extensible programs
- Separate logic and improve code readability
Where are callbacks used?
- JavaScript
The most common area.
Example: handling button clicks, processing data after an AJAX request. - Node.js
Callbacks are used for working with files, network requests, and streams. - APIs and webhooks
A server calls a callback URL when an event occurs (e.g., payment confirmation). - Event-driven systems
Games, interfaces, and applications that respond to user actions. - Filters and middleware
For example, in Express.js or Laravel.
Simple callback example in JavaScript
javascript
function greet(name, callback) {
console.log(“Hello, ” + name);
callback();
}
function sayBye() {
console.log(“Goodbye!”);
}
greet(“Andrey”, sayBye);
Result:
Hello, Andrey
Goodbye!
Asynchronous example with a server
javascript
setTimeout(() => {
console.log(“Loading complete”);
}, 2000);
The function inside setTimeout is a callback that will execute later (after 2 seconds).
Problems with callbacks
Callback Hell
Poorly readable nested functions:
javascript
doA(function() {
doB(function() {
doC(function() {
doD();
});
});
});
Solutions:
- Promises
- async/await
- Clean architecture
Advantages of callbacks
- High flexibility
- Simplified event handling
- Enable asynchronous programming
- Reduce code duplication
Disadvantages
- Risk of “callback hell”
- Harder to debug
- Potential for uncontrolled call flow
Callback in business and marketing (additional)
The word “callback” is sometimes used in another sense—a return phone call.
For example, a “Call me back” button on a website. This is a different meaning of the term, but it is also a type of “callback.”
Summary
A callback is a function or action passed for later execution, after a specific event occurs or an operation completes. It is an essential part of asynchronous programming and event-driven systems.
