liveBook · Manning

Scope

As explained in Secrets of the JavaScript Ninja, Third Edition

Scope determines where bindings are visible and how names are resolved.

Why can a callback still read a local variable after the function that created it has returned? Scope determines where an identifier is visible and which variable its name denotes. A function can access variables that were in scope when it was defined; its closure preserves that access even when the surrounding function has finished executing. Where the callback is later called does not change which surrounding variables it sees. section 7.1

To find a JavaScript binding’s scope, start with its declaration:

  • A module has its own scope, and every function body creates one. Blocks in constructs such as if, for, and switch, as well as standalone blocks, create scopes; object-literal braces do not. section 7.3.1
  • let and const follow block scope. The older var ignores intervening blocks and belongs to the nearest function or module; avoiding it removes a common source of surprises. section 7.3.1
  • A variable declared with let in a for initializer belongs to the loop scope, with a fresh scope for each iteration. Closures created in separate iterations therefore see their respective loop values. section 7.3.1
Listing 7.5 Loop scope and closures
for (let i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 10);
}

Run the timer example: its callbacks print 0, 1, and 2, not three copies of the final loop value. Changing let to var changes the scoping rule that makes this work. section 7.3.1

Visibility is not the same as readiness to use a binding. JavaScript determines which declarations belong to a scope before executing it, but reading a let, const, or class binding before initialization throws a ReferenceError: it is in the temporal dead zone. Execution order matters. A function may mention a later-declared const safely if the function runs only after initialization. Function declarations and imports are exceptions that can be referenced before their declarations execute. section 7.3.2 section 7.6

Under the hood, scope analysis constructs scopes during parsing before execution in that scope, though an engine may defer full parsing until needed. Syntax validation still catches errors such as duplicate declarations before any code runs. This is a useful model, not a promise about every engine’s exact parsing passes. section 7.3.3

Module-level names are not automatically global names. To make a value available across modules without importing it, attach it to globalThis; strict mode rejects assignment to an undeclared name. Finally, a live closure can keep its surrounding scope live. Garbage-collection choices vary by engine, so an unexpectedly retained object calls for investigation rather than an assumption that every captured scope leaks. section 7.4 section 7.5

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through block rules, initialization, and scope analysis, while qualifying the parsing model as an engine simplification.
Examples
Uses nested closures, delayed loop callbacks, pre-initialization errors, globalThis assignments, and a heap-snapshot investigation.
What it assumes
Assumes familiarity with JavaScript functions and declarations while defining scope and developing its block rules explicitly.
What you can do after
Diagnose/debug name-resolution errors, surprising loop callbacks, and possible closure-related memory retention.
How it connects
Connects scope to closures, hoisting, the temporal dead zone, global variables, and garbage collection.

Also explained in

Compare how 24 books explain scope →

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.