Callback

Also known as: callback function

On this page 7

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.

LanguageMechanismTypical form
CFunction pointerint (*cmp)(const void *, const void *)
JavaScriptFirst-class functionarr.map(x => x * 2)
PythonCallable objectsorted(words, key=len)
C#Delegate or lambdalist.ForEach(item => Print(item))
JavaFunctional interfacebutton.addActionListener(e -> save())
Callback mechanisms across languages

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.

PropertySynchronous callbackAsynchronous callback
When it runsBefore the caller returnsAfter the caller returns
Typical usesSorting, mapping, filteringNetwork requests, timers, user events
Call stackSame stack as the callerNew stack from the event loop
Error propagationNormal exceptions workErrors must be passed explicitly
Ordering riskLowHigh if timing is assumed
Comparison of callback timing models

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.

PatternPurposeExample
ComparatorDefine ordering for a generic algorithmCustom sort by date
IterateeApply logic to each elementTransforming a list with map
Event handlerReact to user or system eventsClick listener on a button
Completion handlerReport the result of a slow taskFile read finished
Error-first callbackReturn an error or a result(err, data) => ... in Node.js
Hook or pluginLet users extend a frameworkLifecycle method in a library
Typical callback patterns and their purpose

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.

StyleReadabilityError handlingComposition
Plain callbacksDegrades with nestingManual at every stepDifficult for parallel tasks
Promises or futuresLinear chainsSingle catch handlerBuilt-in helpers such as Promise.all
Async and awaitReads like sequential codeStandard try and catchCombines with promise helpers
Reactive streamsDeclarative pipelinesError channel in the streamStrong for many events over time
Asynchronous styles compared

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.