Notes Tutorials

Variables, state, and scope

Where a variable can be seen, how long it lives, and who is allowed to change it. Scope in Python, JavaScript, and Go, closures, and why shared state causes so many bugs.

7 min readAlso available in Bahasa Indonesia →

The previous part showed that a variable is a name pointing at something in memory. This part asks three follow-up questions about that name: where can it be seen, how long does it live, and who is allowed to change what it points to? Those three questions are what people mean by scope and state, and getting them wrong is behind a large share of everyday bugs.

State: what the program remembers

State is everything a program remembers at a given moment: the values in its variables, the contents of its lists, the rows in its database. Without state, a program could only compute the same output from the same input every time. With state, it can count, keep a shopping cart, or remember who is logged in.

State is also where trouble starts. A value that never changes is easy to reason about. A value that can be changed from many places means that, to understand what it holds right now, you have to know everything that touched it before. Much of this part is about keeping that list short.

Scope: where a name is visible

Scope is the part of the code where a name can be used. The Go specification defines it as “the extent of source text in which the identifier denotes the specified constant, type, variable, function, label, or package.” Python’s tutorial puts it as “a textual region of a Python program where a namespace is directly accessible”, where a namespace is “a mapping from names to objects.”

In plain words: a variable declared inside a function or a block usually exists only there. Code outside can’t see it, and it can’t clash with a variable of the same name elsewhere. That is a good thing. The smaller a variable’s scope, the fewer places can change it, and the easier it is to understand.

Python: functions and the UnboundLocalError surprise

In Python, a variable assigned inside a function is local to that function. That rule produces a confusing error that almost everyone meets once:

count = 0

def increment():
    count = count + 1
    return count

increment()
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

The Python FAQ explains why: “when you make an assignment to a variable in a scope, that variable becomes local to that scope.” Because increment assigns to count, Python treats count as local for the whole function, including the right-hand side of count + 1, where the local count has no value yet.

If you really want to change the outer variable, Python makes you say so. The tutorial: “The global statement can be used to indicate that particular variables live in the global scope and should be rebound there”, and “To rebind variables found outside of the innermost scope, the nonlocal statement can be used.”

def increment_global():
    global count
    count = count + 1
    return count

print(increment_global(), increment_global())  # 1 2

It works, but every function that writes to a global is a place you’ll have to check when that global holds an unexpected value. Most of the time, passing a value in and returning a new one is the cleaner choice.

PHP: functions start with a clean slate

PHP goes further than Python: a function can’t even read outside variables unless you ask. The manual: “Any variable created inside a named function or an anonymous function is limited to the scope of the function body.”

$count = 0;

function show() {
    echo $count;
}
show();
Warning: Undefined variable $count

To use the outer one, “The global keyword is used to bind a variable from a global scope into a local scope”:

function increment() {
    global $count;
    $count = $count + 1;
    return $count;
}
echo increment(), " ", increment();   // 1 2

PHP also has static variables, which keep their value between calls of the same function:

function counter() {
    static $n = 0;
    $n++;
    return $n;
}
echo counter(), " ", counter(), " ", counter();   // 1 2 3

Handy, but it’s state hidden inside a function, with the same downsides as a global.

JavaScript: var, let, and const

JavaScript has three ways to declare a variable, and they differ exactly on scope:

  • var “declares function-scoped or globally-scoped variables”. It ignores blocks like if and for.
  • let declarations “are scoped to blocks as well as functions.”
  • const works like let, but the name can’t be pointed at a new value.

The difference is easiest to see in a loop that schedules work for later:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var", i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let", j), 0);
}
var 3
var 3
var 3
let 0
let 1
let 2

With var, there is one i for the whole function, and by the time the callbacks run, the loop has finished and i is 3. With let, each iteration gets its own j.

const is often misunderstood. MDN: “The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable — just that the variable identifier cannot be reassigned.”

const config = { debug: false };
config.debug = true;      // fine: changing the object
console.log(config.debug); // true
config = {};               // TypeError: Assignment to constant variable.

Two more details explain some confusing errors. var declarations “are processed before any code within the script is executed” (this is called hoisting), but “Only a variable’s declaration is hoisted, not its initialization”, so reading a var early gives undefined instead of an error. A let variable read too early is in a “temporal dead zone”, and “any attempt to access it will result in a ReferenceError”:

console.log(typeof hoisted, hoisted); // undefined undefined
var hoisted = 5;

console.log(total); // ReferenceError: Cannot access 'total' before initialization
let total = 1;

The practical rule most teams use: const by default, let when you really need to reassign, and no var in new code.

Go: blocks and shadowing

Go scopes variables to blocks, and it allows reusing a name in an inner block. The spec: “An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration.” This is called shadowing:

x := 1
if true {
    x := 2               // a new x, only inside this block
    fmt.Println("inside:", x)
}
fmt.Println("outside:", x)
inside: 2
outside: 1

The trap is the :=. Writing x := 2 instead of x = 2 creates a new variable rather than changing the outer one, and the code still compiles. When a value “doesn’t change” in Go, an accidental shadow is one of the first things to check.

Closures: functions that remember

A function can use variables from the scope it was created in, even after that scope has finished. MDN defines a closure as “the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).”

def make_counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step

a = make_counter()
b = make_counter()
print(a(), a(), a(), b())  # 1 2 3 1

Each counter keeps its own private n. Nothing outside can touch it except through step. That is state with a very small scope, which is exactly what you want.

Closures are also why the loop example above behaved the way it did: each callback closed over a variable, and the question was whether that variable was shared or per iteration. Go had the same issue for years, and a 2023 Go blog post announced the plan to “make these variables have per-iteration scope instead of per-loop scope” starting with Go 1.22. On Go 1.24, this now prints each value once:

var printers []func()
for i := 0; i < 3; i++ {
    printers = append(printers, func() { fmt.Print(i, " ") })
}
for _, p := range printers {
    p()
}
// 0 1 2

Why this matters day to day

  • Globals make bugs non-local. When a global or module-level variable holds a wrong value, the cause can be anywhere that writes to it. Keep state as close as possible to the code that uses it.
  • Servers share state between requests. A module-level list or object in a web server is shared by every request and every user. Something meant for one request ends up visible to another.
  • Async code reads variables later. Callbacks, promises, and goroutines run after the surrounding code has moved on. If they read a variable that has changed since, you get last-value bugs like the var loop above.
  • Smaller scope, easier code. A variable used in three lines is trivial to understand. One used across a whole file needs you to read the whole file.

Try it yourself

  1. Run the Python increment example, read the error, then fix it twice: once with global, once by passing count in and returning the new value. Which version is easier to test?
  2. In your browser console, run the var/let loop. Then change var to let in the first loop.
  3. Make a const array and call .push() on it. Then try to assign a new array to it.
  4. In Go, write an if block that accidentally shadows a variable with :=, then fix it with =.

Summary

  • State is what a program remembers; the more places can change it, the harder it is to reason about.
  • Scope is where a name is visible. Smaller scope means fewer surprises.
  • Python makes assigned variables local to the function; PHP functions can’t see outside variables at all. Use global / nonlocal only when you really mean it.
  • In JavaScript, prefer const, then let; avoid var. const locks the name, not the object.
  • Go scopes to blocks, and := in an inner block creates a new, shadowing variable.
  • A closure is a function plus the variables around it; it’s a neat way to keep state private.

References