Skip to content
Devgo

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.

When to use
  • Always — scope is built into every language.
When not to
  • Never.

Definition

Scope defines where a can be referenced. Block scope: variables exist only within { }. 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 hides outer).
  • Scope confusion with this in JS.

,