A callback (or callback function) is a function that is passed as an argument to another function, which then invokes it at a chosen moment to customize its behavior, process each item or deliver a result. In programming, callbacks are one of the most basic ways to separate what code does from when it runs, and they rest on a simple idea from programming fundamentals: a function can be treated as a value.
The function that receives the callback is often called the higher-order function or the caller, while the code that supplies it is the client. The client hands over behavior without knowing exactly when or how often it will run, and the receiving function decides the timing. This inversion of control makes callbacks powerful and, when overused, difficult to reason about.
How a callback is passed and invoked
A callback works because the language supports first-class functions or an equivalent mechanism such as function pointers or delegates. The client passes a reference to the function, not the result of calling it, so writing sort(items, compare) hands over the comparison logic, while sort(items, compare()) would pass whatever compare returns.
Inside the receiving function, the callback is just another parameter. The function invokes it with arguments it controls, such as two elements to compare or an error object, and may use its return value to continue its work. A callback can also be a closure that captures variables from the scope where it was defined, which lets it carry context without global state.
The table below shows how different language families express the same mechanism.
| Language | Mechanism | Typical form |
|---|---|---|
| C | Function pointer | int (*cmp)(const void *, const void *) |
| JavaScript | First-class function | arr.map(x => x * 2) |
| Python | Callable object | sorted(words, key=len) |
| C# | Delegate or lambda | list.ForEach(item => Print(item)) |
| Java | Functional interface | button.addActionListener(e -> save()) |
Synchronous and asynchronous callbacks
Callbacks fall into two families depending on when the call happens relative to the function that received them. The distinction matters because it decides whether code after the call can rely on the callback having already run.
A synchronous callback runs before the receiving function returns. Array methods such as map, filter and reduce, as well as sorting with a custom comparator, call the supplied function immediately and repeatedly. An asynchronous callback is stored and invoked later, after an event, a timer or an input and output operation completes, usually from an event loop or a separate thread.
| Property | Synchronous callback | Asynchronous callback |
|---|---|---|
| When it runs | Before the caller returns | After the caller returns |
| Typical uses | Sorting, mapping, filtering | Network requests, timers, user events |
| Call stack | Same stack as the caller | New stack from the event loop |
| Error propagation | Normal exceptions work | Errors must be passed explicitly |
| Ordering risk | Low | High if timing is assumed |
A frequent source of bugs is an API that is sometimes synchronous and sometimes asynchronous, for example one that returns cached data immediately but fetches fresh data later. Experienced developers call this releasing Zalgo and always choose one timing model per API, deferring the cached case if necessary.
Common callback patterns
Callbacks appear in several recognizable patterns, each solving a different design problem. Knowing the pattern helps a reader predict how often the callback runs and what arguments it receives.
| Pattern | Purpose | Example |
|---|---|---|
| Comparator | Define ordering for a generic algorithm | Custom sort by date |
| Iteratee | Apply logic to each element | Transforming a list with map |
| Event handler | React to user or system events | Click listener on a button |
| Completion handler | Report the result of a slow task | File read finished |
| Error-first callback | Return an error or a result | (err, data) => ... in Node.js |
| Hook or plugin | Let users extend a framework | Lifecycle method in a library |
The error-first convention, popularized by Node.js, reserves the first argument for an error object and the following arguments for results. It gives asynchronous code a predictable shape for error handling, because ordinary try and catch blocks cannot catch an exception thrown later on a different stack.
Callbacks compared with promises and async functions
Callbacks are the lowest-level building block for asynchronous code, and newer abstractions are built on top of them rather than replacing the idea. Promises, futures and async and await syntax still schedule callbacks internally, but they change how those callbacks are composed.
Deeply nested asynchronous callbacks produce the shape known as callback hell or the pyramid of doom, where each step lives inside the previous one and error handling is repeated at every level. Promises flatten this chain and centralize errors, while async functions let the same logic read like sequential code.
| Style | Readability | Error handling | Composition |
|---|---|---|---|
| Plain callbacks | Degrades with nesting | Manual at every step | Difficult for parallel tasks |
| Promises or futures | Linear chains | Single catch handler | Built-in helpers such as Promise.all |
| Async and await | Reads like sequential code | Standard try and catch | Combines with promise helpers |
| Reactive streams | Declarative pipelines | Error channel in the stream | Strong for many events over time |
Callbacks remain the right choice for repeated events and for synchronous customization. A promise resolves only once, so a click listener or a progress handler that fires many times is still naturally expressed as a callback.
Pitfalls and good practice
Because the receiving code controls when and how a callback runs, most problems come from trusting that control too much or from losing context. The following mistakes are common in production code.
- Calling instead of passing: writing
handler()executes the function immediately and passes its result. - Lost `this` binding: in JavaScript, a method passed as a callback may lose its object unless it is bound or wrapped in an arrow function.
- Called twice or never: a careless library may invoke a completion callback more than once, so robust code guards against duplicate invocation.
- Swallowed errors: ignoring the error argument hides failures that later surface as corrupted state.
- Memory leaks: event listeners that are never removed keep their closures and captured objects alive, which blocks garbage collection.
- Stale closures: a callback may capture an old value of a variable, which is a frequent issue with loops and UI state.
Good practice is to keep callbacks small and named, document whether they run synchronously, validate that they are callable, and remove listeners when they are no longer needed. In typed languages, an explicit function type or interface makes the expected signature visible to readers and to the compiler.
Stripped to the essentials
A callback is a piece of code that you hand to someone else and say: run this when the moment is right. You do not run it yourself. The other piece of code decides when.
It is like leaving your phone number at a busy restaurant. Instead of standing at the door, you go for a walk, and the host calls you back when your table is ready. Programs use the same trick to keep working while they wait for a file, a website or a mouse click, and to let general tools such as sorting follow your own rules.
Where it is applied
A developer builds a web dashboard that shows live delivery status for a logistics team. When the page loads, it registers a click callback on a refresh button and requests the latest data from a server, passing a completion callback that receives either an error or a list of about 500 shipments.
While the request is in flight, which typically takes 200 to 800 milliseconds, the browser stays responsive because the event loop is free. When the data arrives, the completion callback runs, sorts the shipments with a custom comparator callback that places delayed items first, and redraws the table. If the network fails, the error argument triggers a visible warning instead of a silent blank screen.
The result is an interface that never freezes while waiting and keeps the sorting rule, the network logic and the button behavior cleanly separated, so each part can be changed or tested on its own.