Scope (programming)
Scope is the region of a program where a variable, function, or other identifier can be accessed and used. It defines the visibility and lifetime of names within code, preventing collisions and organizing complexity.
A function creates its own scope: variables declared inside exist only within that function's boundaries. Assignments made in inner scopes can shadow outer ones—hiding outer variables with the same name. Languages implement scope through different rules: some use block scope (curly braces define boundaries), others function scope (the whole function is one unit), and some even dynamic scope (based on call order rather than code position).
Scope is fundamental to secure coding. By restricting what code can see and modify, programmers reduce bugs, simplify reasoning about behavior, and enable safe module design. The principle mirrors how organizations compartmentalize information—each department needn't know everything.
Misunderstanding scope causes subtle errors: accidental modifications of global variables, or relying on variables that don't exist where you expect them. Modern languages offer increasingly sophisticated scope mechanisms to catch these mistakes at compile-time.
Related
Variable (programming), Function (programming), Closure (programming), Module (programming), Namespace (programming), Static analysis (programming)