Chapter 7: Functions for the master: closures and scopes
The chapter introduction explains why closures matter and connects them to JavaScript scope without yet explaining their mechanics.
After this chapter you will be able to
- Closures and JavaScript scope. Explain that closures arise from how scope works in JavaScript and make common callback-based patterns, such as event handling and animations, less complex.
- Definition-time variable access. Explain that a closure gives a function access to variables and other functions in scope when it is defined, including variables outside the function itself.
- Closure lifetime and retained variables. Explain why variables from a function's original scope remain available after that scope finishes executing, and how long the closure keeps them available.
- Memoization cache scope and lifetime. Explain that each call to memoize creates a separate cache accessible only to its returned function, and that the cache remains in memory while a live reference to that function exists.
- Callback access to surrounding variables. Explain how a callback can reference variables in its lexical scope, including a variable declared after the callback function, provided that variable is initialized before the callback accesses it.
- Block and module scopes. Describe how modules, control-flow constructs, and standalone blocks create scopes. Explain that curly brackets usually indicate a block scope, while a for-loop initializer belongs to the loop’s scope.
- Per-iteration loop values. Explain why timer callbacks created in a for loop with let i each see the i value from their own iteration, even though they run after the loop. Distinguish this from var i, which would make them see the final value.
- Scope and temporal dead zone. Explain why a variable can be in scope yet throw a ReferenceError when referenced before initialization, and distinguish that case from an undeclared name and an uninitialized var.
- Initialization and execution order. Explain why a function body may mention a variable before its declaration appears in the code without causing an error.
- Function declaration hoisting. Describe how hoisting lets a function declaration be called from anywhere in its scope, and distinguish function declarations from functions defined with other syntax.
- Parsing and scope construction. Explain how parsing lets the engine identify variables in a scope before their declarations execute, and distinguish syntax validation from full parsing and scope analysis.
- Upfront syntax validation. Explain why a syntax error can prevent even earlier statements from running, and how checking all code affects startup time.
- Deferred full parsing. Explain how lazy parsing can shorten startup time and apply the section’s CLI example to show why moving complex logic into a function helps.
- Intentional global object values. Describe how to make a value accessible across modules without an import by attaching it to the global object.
- Scope chain name resolution. Trace how a variable reference is resolved from the local scope toward the global scope, including when it throws a ReferenceError.
- Checks for undeclared globals. Distinguish checking a possibly undeclared global with typeof from checking an uninitialized local variable.
- Closure-related object retention. Trace why powerBuffer remains in memory in the example even after the IIFE finishes. Explain the difference between retaining prepareNinjaPower’s returned function and discarding it.
What it builds on
- Callback functions (chapter 5) · Introduces callback functions, used here as an example of where closures matter.
- Function declarations and function expressions (chapter 5) · Recognizing function declarations and where they are defined.
- Memoizing functions (chapter 5) · The earlier introduction of memoizing functions.
Section by section
Introduction
The chapter introduction explains why closures matter and connects them to JavaScript scope without yet explaining their mechanics.
- Closures and JavaScript scope: Explain that closures arise from how scope works in JavaScript and make common callback-based patterns, such as event handling and animations, less complex.
Why it matters: This connection gives you a reason to study scope when learning about closures.
Key terms: closures, scopes, callbacks
7.1 Understanding closures
This section explains how closures let functions use variables from the scope where they were defined, even when called after that scope has finished executing.
- Scope and identifier visibility: Explain that a scope determines where an identifier is visible and which variable its name refers to.
Why it matters: Scope explains which surrounding variables a function can access. - Definition-time variable access: Explain that a closure gives a function access to variables and other functions in scope when it is defined, including variables outside the function itself.
Why it matters: It explains why moving or calling a function elsewhere does not change which surrounding variables it can use. - Closure lifetime and retained variables: Explain why variables from a function's original scope remain available after that scope finishes executing, and how long the closure keeps them available.
Why it matters: It explains how a function can still use surrounding variables long after their original scope has finished executing.
Key terms: scope, identifiers, closure, innerFunction, outerValue, innerValue, garbage-collecting
7.2 Putting closures to work
Introduces a practical look at closures and defers their underlying mechanics to later in the chapter.
7.2.1 Saving values in function-scoped variables
The section uses memoization to show how function scope gives a returned function access to a private cache and keeps that cache alive while the function is referenced.
- Memoization cache scope and lifetime: Explain that each call to memoize creates a separate cache accessible only to its returned function, and that the cache remains in memory while a live reference to that function exists.
Why it matters: This explains how a memoized function can keep its cache without exposing it to other code. - Function scope as private access: Describe how restricting access through function scope approximates private variables, and why the section says this remains useful despite the addition of private variables in classes.
Why it matters: It connects the cache example to the broader use of function scope for controlling access.
Key terms: memoize, cache, scope, live references, function scope, private variables
7.2.2 Referencing surrounding variables from callbacks
Shows how a callback can use surrounding variables, including one declared after the callback function, if it is initialized before the callback accesses it.
- Callback access to surrounding variables: Explain how a callback can reference variables in its lexical scope, including a variable declared after the callback function, provided that variable is initialized before the callback accesses it.
Why it matters: This explains why a callback can use values from the code around it when it runs later.
Key terms: closures, callbacks, lexical scope, tick, timerId
7.3 Variable scope and hoisting
Introduces the upcoming discussion of JavaScript scope and hoisting without explaining either concept in depth.
7.3.1 Creating block scopes
Explains how JavaScript creates scopes without functions and why let gives loop callbacks a separate value for each iteration.
- Block and module scopes: Describe how modules, control-flow constructs, and standalone blocks create scopes. Explain that curly brackets usually indicate a block scope, while a for-loop initializer belongs to the loop’s scope.
Why it matters: Recognizing where scopes begin helps you tell which part of the code a variable belongs to. - Per-iteration loop values: Explain why timer callbacks created in a for loop with let i each see the i value from their own iteration, even though they run after the loop. Distinguish this from var i, which would make them see the final value.
Why it matters: This explains why delayed callbacks can report different loop values rather than all reporting the last one.
Key terms: module scope, block scope, standalone block, for loop initializer, for loop block scope, closure, let, var, timer callback
7.3.2 Execution order and hoisting
This section explains why a name can be in scope but not yet usable, why execution order matters for variable references, and how function declarations are hoisted.
- Scope and temporal dead zone: Explain why a variable can be in scope yet throw a ReferenceError when referenced before initialization, and distinguish that case from an undeclared name and an uninitialized var.
Why it matters: It helps explain why an early reference fails even when the declaration appears later in the same scope. - Initialization and execution order: Explain why a function body may mention a variable before its declaration appears in the code without causing an error.
Why it matters: It lets you judge whether a reference is safe by when the code runs rather than where the reference is written. - Function declaration hoisting: Describe how hoisting lets a function declaration be called from anywhere in its scope, and distinguish function declarations from functions defined with other syntax.
Why it matters: It explains why a call before a function declaration works without implying that every way of defining a function behaves alike.
Key terms: scope, Temporal Dead Zone, ReferenceError, let, const, class, execution order, initialized, referenced, function declaration
7.3.3 Parsing and scope analysis
This section explains how pre-execution syntax validation and scope analysis affect JavaScript behavior and startup time.
- Parsing and scope construction: Explain how parsing lets the engine identify variables in a scope before their declarations execute, and distinguish syntax validation from full parsing and scope analysis.
Why it matters: This connects what code can reference to work the engine does before executing that scope. - Upfront syntax validation: Explain why a syntax error can prevent even earlier statements from running, and how checking all code affects startup time.
Why it matters: It explains both why an error stops a script immediately and why code size affects startup. - Deferred full parsing: Explain how lazy parsing can shorten startup time and apply the section’s CLI example to show why moving complex logic into a function helps.
Why it matters: It shows why putting substantial work inside a function can let a program respond sooner.
Key terms: syntax validation, full parsing, scope analysis, syntax error, startup time, lazy parsing, outer scope, handleInput function
7.4 The global scope object
This section explains how globals are created and accessed, how the scope chain resolves names, and how to check for a possibly undeclared global.
- Accidental globals and modules: Explain how assigning to an undeclared name could create or overwrite a global, and why modules and strict mode reduce that risk.
Why it matters: It distinguishes an accidental global from an ordinary module-level variable. - Intentional global object values: Describe how to make a value accessible across modules without an import by attaching it to the global object.
Why it matters: It provides the section’s deliberate alternative to accidentally creating a global. - Portable global object reference: Explain why globalThis is preferred when referring to the global object across JavaScript environments.
Why it matters: It avoids choosing a global-object name that works in only one runtime. - Scope chain name resolution: Trace how a variable reference is resolved from the local scope toward the global scope, including when it throws a ReferenceError.
Why it matters: It explains both where a referenced name gets its value and why some references fail. - Checks for undeclared globals: Distinguish checking a possibly undeclared global with typeof from checking an uninitialized local variable.
Why it matters: It keeps a safe check for a missing global from being mistaken for a way around local initialization errors.
Key terms: global variable, module’s scope, strict mode, global object, globalThis, window, global, scope chain, local scope, global scope
7.5 Preventing memory leaks
This section explains how closures can keep large objects in memory longer than needed and why garbage collection may not remove them.
- Closure-related object retention: Trace why powerBuffer remains in memory in the example even after the IIFE finishes. Explain the difference between retaining prepareNinjaPower’s returned function and discarding it.
Why it matters: A function you keep can indirectly keep a large object alive after you are done with it. - Garbage-collection heuristic tradeoff: Explain why an object in a live scope is not guaranteed to be collected and why the engine does not simply track every closure’s variable references more precisely.
Why it matters: A live scope does not give you a portable guarantee about when an unneeded object will be freed. - Explicit large-object cleanup: State the section’s recommended response when it is uncertain whether the engine will collect a large object that is no longer needed.
Why it matters: Explicit cleanup avoids depending on uncertain garbage-collection behavior for a large object.
Key terms: closure, scope, powerBuffer, garbage-collected, IIFE, garbage collection, ECMAScript spec, heuristics, V8, explicitly delete
7.6 Summary
Concepts explained in this chapter
- scopeScope determines where bindings are visible and how names are resolved.
- temporal dead zoneThe interval from entering a lexical declaration's scope until its initialization during which accessing the binding throws an error.
- constantconst is a JavaScript keyword that declares a block-scoped binding that must be initialized and cannot be reassigned.
- let keywordlet is a JavaScript keyword that declares a block-scoped, reassignable binding.
- varvar is a JavaScript declaration keyword for creating a function-scoped binding that is initialized to undefined during scope setup.
- closureA closure is a function together with access to variables from its surrounding lexical environment.
- global scopeThe global scope is the outermost JavaScript scope whose bindings are available across a script or execution environment.
- globalThisThe standardized JavaScript global binding that references the global object across different execution environments.
- global objectThe top-level object that provides globally accessible bindings for a JavaScript execution environment.
- typeof operatorThe JavaScript typeof operator returns a string indicating the basic type of its operand.
- callbackA function supplied to another computation to be invoked when a specified event occurs or operation completes.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
