liveBook · Manning

Scope

As explained in Functional Programming in JavaScript

Scope is the region of program text in which a binding name refers to a particular variable or function declaration.

Scope is the region of program text where a variable or function name refers to a particular declaration. JavaScript looks in the closest surrounding scope first, then moves outward through parent and global scopes. section 2.4

Functions retain access to surrounding bindings through lexical scope. This closure behavior lets returned functions use parameters and local variables after the outer function finishes, supporting private variables, callbacks, and higher-order functions. section 2.4

JavaScript scope behavior includes:

  • Block-level scope prevents loop and conditional bindings from leaking into surrounding code, avoiding ambiguous counters and related bugs. section 2.4

A returned function remembers its scope

makeAddFunction(10) returns add, which still uses amount when called later; addTenTo(10) produces 20.

How Functional Programming in JavaScript covers it

How deep it goes
Defines lexical, function, global, and block scope, then demonstrates lookup, closures, var leakage, and loop-counter problems.
Examples
Uses nested functions, returned adders, private accessors, name lookup, var conditionals, and an ambiguous loop counter.
What it assumes
Assumes basic JavaScript functions and variables while building scope and closure behavior from concrete nested-function examples.
What you can do after
Evaluate JavaScript name lookups and use closures to preserve state or emulate private variables.
How it connects
Connects scope with closures, lexical scope, function scope, global scope, block scope, callbacks, and higher-order functions.

Also explained in

Compare how 21 books explain scope →

Related concepts

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