Sknoe / Notes
JavaScript Callbacks Explained: How They Work and Why They Matter
Understand how callbacks work in JavaScript, why functions are passed as arguments, and how this pattern powers event handlers, array methods, and asynchronous code.
Callbacks show up throughout JavaScript, but often the function is defined far from where it runs. That can make a line like `(Rule) => Rule.required()` in a Sanity schema feel mysterious: who calls this function, what is `Rule`, and when does the callback run?
A callback is a function passed to other code so the receiving code can call it. In the Sanity example, your schema gives Sanity a callback; Sanity supplies a Rule builder and calls the function to configure a required-field validation rule. We’ll use that familiar example to unpack the general idea, then compare it with array methods, timers, browser events, and React.
A function can be passed as a value
JavaScript lets you store a function in a variable, pass it to another function, and call it later. Here, `processValue` receives a callback and calls it with the value `4`:
function processValue(value, callback) {return callback(value);}function double(number) {return number * 2;}const result = processValue(4, double);console.log(result); // 8
The call `processValue(4, double)` passes two arguments: the number `4` and the function `double`. Inside `processValue`, the parameter named `callback` refers to that same function. Calling `callback(value)` is what runs `double(4)`. The name `callback` is just a parameter name; it doesn’t have special meaning to JavaScript.
Who calls the callback? It depends on the API
There isn’t one universal caller. The function you pass is called by whatever code receives it. The API’s documentation or implementation tells you when it runs and what arguments it receives. Compare these common cases.
Array methods call back for array items
When you call `map`, the array method calls your callback for each item and uses each returned value to build a new array:
const prices = [10, 20, 30];const pricesWithTax = prices.map((price) => price * 1.1);console.log(pricesWithTax); // [11, 22, 33]
You provide the transformation; `map` supplies each `price` and collects the returned values. The callback can also receive the item’s index and the original array. You don’t call it yourself in this example because `map` does that work.
A timer calls back later
With `setTimeout`, you pass a function for the timer system to call after the delay:
setTimeout(() => {console.log('The timer finished');}, 1000);
The arrow function is passed to `setTimeout`; it is not called at the moment it is passed. The timer schedules it to run after roughly one second. This is an example of a callback that runs later, while the `map` callback above runs as the array method processes the array.
Under the hoodA callback does not define when it runs
Looking closer
A call to `map` invokes its callback while `map` is running. `setTimeout` asks the runtime to invoke its callback after a delay. Browser event APIs invoke a handler when the relevant event occurs. A Promise's `then` method arranges for a handler to run after the promise settles. The word callback describes the function’s role in the handoff; it does not, by itself, promise that the function runs later. Check the receiving API to understand timing and arguments.
Callbacks in browser events and React
A browser event listener is another familiar callback pattern. You give the browser a function, and the browser calls it when the event happens, passing an event object:
button.addEventListener('click', (event) => {console.log('Clicked element:', event.currentTarget);});
React uses a similar handoff for event handlers. You provide a function as the `onClick` prop; React calls it in response to a click and provides an event object. Notice that we pass `handleClick`, without parentheses. Writing `handleClick()` would call it immediately while rendering and pass its return value instead.
function SaveButton() {function handleClick(event) {console.log('Save clicked', event);}return <button onClick={handleClick}>Save</button>;}
This connects callbacks to the Sanity schema example. In `validation: (Rule) => Rule.required()`, Sanity receives your function and calls it with a rule builder. In React, the event system receives your function and calls it with an event when someone clicks. In both cases, the receiving API determines the timing and argument.
What to learn next
Objects are data; functions do work
Functions can be passed around as values
Build on the idea that JavaScript treats functions as values you can store and pass.
map(), filter(), find(), and reduce()
Array methods use callbacks for different jobs
Compare transforming, selecting, locating, and accumulating array data.
React event handlers
Frameworks call callbacks in response to user actions
Learn how handler functions connect user events to component behavior.
The next time you see a function passed into another function, look for the handoff: identify the receiving API, find where it calls the function, and check what arguments it supplies. That tells you who calls the callback and what the callback is being asked to do.
Did this click?
Tap the bulb if this explanation helped.
Further reading
- Functions
- Array.prototype.map()
- Element: click event
- Responding to Events
- Errors: error-first callbacks
- The `this` keyword
- Introducing asynchronous JavaScript
Interview questions
What is a callback in JavaScript?
A callback is a function passed to other code so that code can call it at a chosen point, often with a value or event as an argument.
Who calls a callback function?
The code or API that receives the function calls it. That API determines when the callback runs and which arguments it receives.
Why pass `handleClick` instead of calling `handleClick()`?
Passing `handleClick` gives React the function to call when the click happens. Calling `handleClick()` runs it immediately during rendering and passes its return value instead of the function.
What arguments does the `Array.prototype.map()` callback receive?
`map()` calls the callback with the current element, its index, and the original array, in that order. The callback’s return value becomes the corresponding item in the new array returned by `map()`.
Does passing a callback mean it runs immediately?
No. Passing a function does not run it. The receiving code decides when to invoke it; for example, map calls its callback while processing an array, while setTimeout schedules its callback to run later.
What does `this` refer to when an object method is passed as a callback?
It depends on how the receiving API invokes the callback; passing a method by itself does not preserve its original object as `this`. Use `method.bind(object)` or a wrapper such as `() => object.method()` when the callback needs that object.
How do Node.js-style error-first callbacks pass errors and results?
The callback receives the error as its first argument and the result as its next argument, commonly `callback(error, result)`. Check the error first; when the operation succeeds, the error argument is usually `null` or otherwise falsy.
What is callback hell, and when can promises or `async`/`await` help?
Callback hell describes deeply nested callback-based code that becomes difficult to read and maintain. Promises and `async`/`await` can make sequential asynchronous steps easier to follow, though callbacks remain useful for events and APIs designed around them.