liveBook · Manning

Callback

As explained in Secrets of the JavaScript Ninja, Third Edition

A function supplied to another computation to be invoked when a specified event occurs or operation completes.

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

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines callbacks through call flow and worked uses, then examines closures, thread blocking, and nested-callback tradeoffs.
Examples
Demonstrates function arguments, mousemove handling, array sorting, file reads, timer intervals, and regex replacement.
What it assumes
Assumes familiarity with functions and arguments while teaching how passing and invoking a function creates a callback.
What you can do after
Apply callbacks to event handlers and API operations while recognizing when blocking code or deep nesting becomes a problem.
How it connects
Connects callbacks to first-class functions, closures, event handling, promises, and async/await.

Also explained in

Compare how 23 books explain callback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.