/skoʊp/
noun … “Where a variable is visible and accessible.”
Scope is the region of a program in which a variable, function, or object is accessible and can be referenced. Scope determines visibility, lifetime, and the rules for resolving identifiers, and it is a fundamental concept in programming languages. Understanding scope is essential for managing state, avoiding naming collisions, and enabling features like closures and modular code.
Key characteristics of scope include:
- Lexical (static) scope: visibility is determined by the physical structure of the code. Variables are resolved based on their location within the source code hierarchy.
- Dynamic scope: visibility depends on the call stack at runtime, where a function may access variables from the calling context.
- Global scope: variables accessible from anywhere in the program.
- Local scope: variables confined to a specific block, function, or module.
- Shadowing: inner scopes can define variables with the same name as outer scopes, temporarily overriding the outer variable.
Workflow example: In JavaScript, variable accessibility depends on lexical structure:
let globalVar = 5
function outer() {
let outerVar = 10
function inner() {
let innerVar = 15
print(globalVar) -- Accessible: 5
print(outerVar) -- Accessible: 10
print(innerVar) -- Accessible: 15
}
inner()
}
outer()
print(globalVar) -- Accessible: 5
print(outerVar) -- Error: undefined
Here, globalVar is in global scope, outerVar is local to outer, and innerVar is local to inner. The inner function forms a closure over outerVar.
Conceptually, scope is like the rooms in a house. Items (variables) are accessible only in the room where they exist, or in connected rooms depending on the rules. A closure is like carrying a small room in your backpack wherever you go.