liveBook · Manning

Callback

As explained in The Joy of JavaScript

A callback is a function passed as an argument to another function to be invoked later or in response to an event or condition.

A callback is a function passed to another function so it can run later, often after asynchronous work, an event, or a condition. Callbacks communicate a sequence such as “do something, then do something else,” but deeply nested callbacks can make asynchronous control flow harder to follow. section 8.2

Callbacks are an application of JavaScript’s first-class and higher-order functions: functions can travel as arguments or return values. Passed around as callbacks, they compose behaviorally by representing sequences of computational logic. section 4.0

Callback-based designs commonly appear in these forms:

  • Event-driven operations, such as mouse events and HTTP requests, invoke supplied functions when the relevant event occurs. section 8.2
  • Node.js-style asynchronous APIs often use error-first callbacks, handling an error before consuming returned data. section 8.2
  • Promises provide a flatter alternative for sequencing asynchronous operations, while preserving the same broad “later, do something else” relationship. section 8.2

An error-first file-reading callback

fs.readFile('blocks.txt', (err, data) => { if (err) throw err; console.log(data); }); The callback receives either an error or the resulting data after the nonblocking operation completes. section 8.2

fs.readFile('blocks.txt', (err, data) => {
 if (err) throw err;
 console.log(data);
});

Use the file-reading listing to inspect the callback signature and see how asynchronous completion is handled without a synchronous blocking call. section 8.2

How The Joy of JavaScript covers it

How deep it goes
Defines callbacks, relates them to the event loop, and contrasts them with Promises; it stops short of detailed runtime internals.
Examples
Uses mouse events, HTTP requests, error-first file reads, and chained asynchronous operations as examples.
What it assumes
Assumes familiarity with JavaScript functions while connecting callbacks to first-class and higher-order function behavior.
What you can do after
Apply callbacks to represent asynchronous follow-up work and compose behavioral sequences in JavaScript.
How it connects
Connects callbacks to higher-order functions, functional programming, Promises, async/await, and the event loop.

Also explained in

Compare how 19 books explain callback →

Related concepts

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