Block-local state
Prevent temporary variables from escaping a conditional or loop.
JS Puzzles · Const
Lexical scope determines where JavaScript resolves names: from the current lexical environment outward through its enclosing environments. Blocks, functions, and scripts form environments, with let and const providing block-scoped bindings.
JavaScript resolves a variable by starting in the current lexical environment and moving through its outer environments until it finds a matching binding. Blocks, functions, and the whole script have lexical environments, while let and const create block-scoped bindings.
const phrase = "Hello";
function say(name) {
console.log(`${phrase}, ${name}`);
}
say("JavaScript");The function can read phrase because its lexical environment points to the surrounding script environment.
Prevent temporary variables from escaping a conditional or loop.
Organize helper functions that read configuration from an enclosing scope.
Understand shadowing and diagnose unresolved-name errors.
A lexical environment stores local bindings and a reference to the outer lexical environment. Variable lookup begins in the current environment and continues outward until a matching binding is found or the global environment is reached.
Follow-up: What happens when a nested block declares the same name as an outer block? The inner binding is found first, so it shadows the outer binding within the nested block.
A block creates a scope for let and const declarations. A variable declared in that block is available only from the block that encloses it.
Follow-up: How does var differ? var is function-scoped rather than block-scoped, so a block alone does not limit its visibility.
A function call creates a new lexical environment containing its parameters and local variables. That environment links to the environment surrounding the function, allowing the function body to resolve outer names.
Follow-up: Why can a returned nested function retain access to outer variables? The nested function keeps the lexical environment in which it was declared.
Lexical EnvironmentEnvironment Recordletconstvarblock scopefunction scopeclosure