A callback is a function passed to another function for that function—or other code—to invoke. It might run immediately, when an event occurs, or when an operation completes. JavaScript can pass functions as arguments because functions are first-class objects. Passing a function does not, by itself, make the call asynchronous. section 5.2.1 section 5.2.2
The smallest callback
In `function call(callback) { return callback(); }`, the caller can supply `() => "done"`. The receiving function invokes its parameter, so `call(() => "done")` returns `"done"` immediately. The important distinction is between passing the function and calling it. section 5.2.1 section 5.2.2
The same mechanism serves different jobs:
- An event listener calls a supplied function on a mouse movement; an array’s `sort` method calls a supplied comparison function to order values. section 5.2.2
- In Node.js, `fs.readFile` accepts a function to run when reading finishes. The single JavaScript thread can handle other requests meanwhile, but a callback cannot run while JavaScript code is blocking that thread. section 3.1
- A `replace` call can invoke a replacer function for each regular-expression match, passing the match, captures, position, and source string. section 12.5
Listing 7.3 Using a closure in a timer interval callback
let tick = 0;
const timerId = setInterval(() => { #A
tick++;
console.log(`tick ${tick}`);
if (tick === 5) { #B
clearInterval(timerId); #B
} #B
}, 10);
A timer callback increments `tick` and, on its fifth run, clears `timerId`. Its closure can access both surrounding variables; `timerId` must be initialized before the callback uses it. section 7.2.2
Callbacks keep event-driven code flexible, but a sequence of asynchronous operations can turn into hard-to-read nesting. Moving callbacks into named functions reduces nesting while making shared state harder to pass along. Promise-based APIs with `await` offer a more linear form without giving up non-blocking I/O. section 8.2.1 section 3.1






















