Learning path

Full curriculum

Full curriculum

Unit content

Scope and local state

A name in a program is not necessarily visible everywhere. Scope is the region of program text in which a name can be referred to.

Local variables

A variable created inside a function is commonly local to that function call:

function area(width, height):
    result = width * height
    return result

The name result is an implementation detail of the function and need not exist outside it.

Nested scopes

Many languages use lexical scope: the scopes visible at a point are determined by the nested structure of the source code.

An inner scope can usually read names from an enclosing scope unless it introduces a new binding with the same name.

Shadowing

When an inner scope defines a name that is already used outside it, the inner binding can shadow the outer one. The two names look identical in source text but refer to different bindings in their respective scopes.

Scope and lifetime

Scope concerns where a name can be referenced. Lifetime concerns how long the associated value or storage continues to exist while the program runs. These concepts are related but not identical.

Keeping state local limits the number of places that can change it, which makes larger programs easier to reason about and decompose.