Overview
Scope determines the visibility and lifetime of variables and functions in different parts of a program. It defines where an identifier can be accessed and where it is hidden from other parts of the code.
Core Concepts
- Global Scope: Variables declared outside any function or block. They are accessible from anywhere in the program.
- Local / Function Scope: Variables declared inside a function. They are only accessible within that function.
- Block Scope: Variables declared inside curly braces
{}(e.g., in anifstatement or aforloop). In modern JS,letandconstare block-scoped. - Lexical Scope (Static Scope): The scope of a variable is determined by its position within the source code. Inner functions have access to variables declared in their outer (parent) scopes.
- Scope Chain: The process by which the engine looks for a variable: it checks the current scope, then the parent scope, and so on, up to the global scope.
Code Examples
const globalVar = "I am global"; // Global Scope
function outer() {
const outerVar = "I am in outer"; // Local to outer()
function inner() {
const innerVar = "I am in inner"; // Local to inner()
console.log(globalVar); // Accessible via Scope Chain
console.log(outerVar); // Accessible via Scope Chain
}
inner();
// console.log(innerVar); // Error: innerVar is not defined here
}
outer();
Use Cases
- Encapsulation: Using local scope to hide implementation details and prevent external code from accidentally modifying internal state.
- Namespace Management: Avoiding naming collisions by keeping variables localized to the functions that need them.
- Closures: A function that “remembers” its lexical scope even when executed outside that scope.
Gotchas
- Global Namespace Pollution: Overusing global variables increases the risk of bugs and makes the code harder to reason about.
- Hoisting: In some languages (like JS), variable and function declarations are moved to the top of their scope during compilation, which can lead to confusing
undefinedvalues if not managed. - Shadowing: When a variable in an inner scope has the same name as one in an outer scope, “shadowing” the outer variable and making it temporarily inaccessible.
