Variable scope

On this page 7

Variable scope is the region of program text in which a variable name is bound and can be referenced. In programming, scope decides which declaration a name refers to, prevents unrelated parts of a program from interfering with each other, and is one of the fundamentals that every language defines, usually through blocks, functions, modules and the global level.

Scope is related to, but distinct from, lifetime: scope is a compile-time property of names, while lifetime describes how long the underlying storage exists at run time. A local variable in C has block scope and automatic lifetime, whereas a closure variable in JavaScript can outlive the function call that created it.

How scope resolves a variable name

When code uses a name, the compiler or interpreter searches nested scopes from the innermost outward until it finds a matching declaration. Each block, function or module creates a new environment or symbol table, and these environments form a chain that ends at the global or built-in scope.

If no declaration is found, the result depends on the language: a compile-time error in Java, C# or Rust, a NameError in Python, or, in non-strict JavaScript, an accidental global variable. When an inner scope declares the same name as an outer one, the inner declaration shadows the outer variable for the rest of that inner region.

The following table lists the common scope levels found across mainstream languages.

Scope levelCreated byVisible toTypical languages
Block scopeBraces or indented blockCode inside that blockC, Java, JavaScript let
Function scopeFunction bodyWhole function bodyJavaScript var, Python
Module scopeSource file or moduleCode within the modulePython, ES modules, Go
Class scopeClass or object bodyMembers and methodsJava, C++, C#
Global scopeTop level of a programEntire programC, JavaScript, PHP
Common levels of variable scope

Lexical scope versus dynamic scope

Almost all modern languages use lexical scope, also called static scope, in which a name is resolved by where the code is written in the source. The alternative, dynamic scope, resolves a name by the chain of active function calls at run time, so the same function can see different variables depending on who called it.

PropertyLexical scopeDynamic scope
Resolution basisPosition in source textCurrent call stack
PredictabilityHigh, readable from codeLow, depends on callers
Closure supportNatural and efficientDifficult to reason about
Tool supportEasy static analysisHard to analyze statically
ExamplesPython, JavaScript, Rust, JavaEarly Lisp, Bash locals, Emacs Lisp default
Lexical and dynamic scope compared

Lexical scope is what makes closures possible: a function defined inside another function captures the variables of its enclosing scope and can use them after the outer function has returned. Callbacks, event handlers and factory functions rely on this behavior, which is why closures appear throughout asynchronous code.

Scope rules differ in details that regularly surprise developers moving between languages. Python follows the LEGB rule, searching local, enclosing, global and built-in scopes in that order, and it treats a name as local if it is assigned anywhere in the function, which produces an UnboundLocalError when it is read before the assignment.

LanguageKey ruleCommon pitfall
PythonBlocks such as if and for create no scopeLoop variable remains after the loop
JavaScriptlet and const are block scopedvar is hoisted to function scope
C and C++Block scope with static storage optionsReturning a pointer to a local
JavaBlock scope; no shadowing of localsLambdas need effectively final locals
GoBlock scope with short declarations:= shadows an outer variable
Selected scope behaviors by language

To modify an outer variable, some languages require an explicit declaration. Python uses the global and nonlocal keywords, while PHP requires global or a use clause for closures. In contrast, JavaScript and Ruby blocks can assign to enclosing variables directly, which is convenient but makes unintended mutation easier.

Choosing the narrowest useful scope

The widely accepted guideline is to declare each variable in the narrowest scope that serves its purpose, as close as possible to its first use. Narrow scope reduces coupling, shortens the code a reader must inspect, and lets compilers and garbage collection reclaim resources sooner.

SituationRecommended scopeReason
Loop counter or temporary resultBlock scopeNot needed after the loop
Value shared by helper functionsModule or class scopeEncapsulates related state
Configuration read once at startupModule constantSingle source, immutable
State kept between callback callsClosure variablePrivate and persistent
Mutable data used everywhereAvoid; pass as parameterGlobals hide dependencies
Scope decisions for common situations

Passing data through a parameter and a return value instead of a shared outer variable makes a function easier to test and reuse, because its behavior then depends only on its inputs.

Common scope errors and misconceptions

  • Accidental globals: assigning to an undeclared name in non-strict JavaScript creates a global variable; strict mode turns this into an error.
  • Loop closure capture: closures created in a loop with var all share one variable, so every callback sees the final value; block-scoped let creates a fresh binding per iteration.
  • Unintended shadowing: an inner variable with the same name hides the outer one, and linters flag this because updates to the inner copy never reach the outer variable.
  • Confusing scope with lifetime: a static local variable in C has block scope but lives for the whole program.
  • Hoisting misread as scope: hoisting moves declarations, not initializations, and let variables sit in a temporal dead zone until their declaration runs.

Most of these problems are caught by static analysis tools and linters, such as ESLint rules against shadowing or Pylint warnings for redefined names, so enabling them is a cheap and effective safeguard.

Put simply

Variable scope is about where a name is known. Think of a large office building. A note pinned inside one meeting room is visible only to people in that room, while an announcement in the main lobby is visible to everyone who enters the building.

In a program, a variable created inside a small section of code is like the note in the meeting room: only that section can see it. Keeping most names private to small sections prevents different parts of a program from accidentally changing each other’s data.

In practice

A web developer writes a page with five buttons and attaches a click handler to each one in a loop. The handlers are meant to report the button number, but every click reports 5. The cause is that the loop counter was declared with var, which has function scope, so all five handlers share a single variable that already holds its final value.

The developer changes the declaration to let, which has block scope and creates a new binding for every iteration of the loop. Each handler now captures its own counter, and the buttons report 0 through 4 as intended.

To prevent a repeat, the team enables the ESLint rules no-var and no-loop-func in its build pipeline. The fix took one keyword, and the linter now catches the same pattern automatically before code reaches review.