Scope
The region of code where a variable or name is visible and accessible. Scopes prevent name collisions and manage lifetimes. Block scope (let/const in JS), function scope (var), and module scope are common. Understanding scope is essential to avoid bugs.
- Always — scope is built into every language.
- Never.
Definition
Scope defines where a variable can be referenced. Block scope: variables exist only within { }. Function scope: within the function. Module scope: within the file/module. Lexical (static) scope is determined by code structure; dynamic scope by call stack (rare).
Why it exists
To prevent variables from leaking everywhere, causing name collisions and unexpected mutations. Scope gives variables a controlled lifetime and visibility.
How it works
When code references a name, the language looks it up in the current scope, then outer scopes, until found or it errors. Variables are destroyed when their scope ends (enabling garbage collection). Closures capture variables from their enclosing scope.
Scaling limits
Not applicable.
Cost shape
Free.
Alternatives
- Global everything — Simple but causes name collisions and bugs.
Failure modes
- Accidental globals (missing var/let in JS).
- Shadowing (inner variable hides outer).
- Scope confusion with this in JS.