liveBook · Manning

Scope

As explained in JavaScript in Depth

The lexical region that determines which variable bindings are visible to code.

A closure can retain far more than its callback appears to use. In a request handler, a delayed callback that needs only parsed.userId may nevertheless keep rawBody reachable because both variables belong to the enclosing function scope. The multi-megabyte body can therefore survive until the timer runs. section 9.1.1

Scope is also a garbage-collection concern: it supplies reachability paths. Assigning rawBody = null removes one path, but restructuring the code so the closure receives only userId prevents the unwanted path from existing. section 9.1.1

Use these rules when delayed work captures data:

  • Inspect every variable in the enclosing function scope, not only the values referenced visibly inside the callback. section 9.1.1
  • Prefer passing a small derived value into a separate scheduling function over exposing a large object to the closure. section 9.1.1
function processRequest(rawBody) {
  const parsed = JSON.parse(rawBody);
 
  setTimeout(() => {
    sendNotification(parsed.userId);
  }, 5000);
}

Shows the retention-prone request handler, where the callback's enclosing scope can keep rawBody reachable. section 9.1.1

function scheduleSendNotification(userId) {
  setTimeout(() => {
    sendNotification(userId)
  }, 5000);
}
function processRequest(rawBody) {
  const userId = JSON.parse(rawBody).userId;
  scheduleSendNotification(userId);
}

Shows the safer restructuring: extract userId and give the timer closure access only to that small value. section 9.1.1

How JavaScript in Depth covers it

How deep it goes
Explains function scope through closure reachability and garbage-collector paths, but does not develop a general scope taxonomy.
Examples
Uses a delayed request notification that accidentally retains rawBody, then restructures it to capture only userId.
What you can do after
Diagnose closure-related retention and reduce it by limiting the values exposed to delayed callbacks.
How it connects
Connects scope with closures, reachability, garbage collection, and delayed callbacks.

Also explained in

Compare how 24 books explain scope →

Related concepts

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