Variables & State

Difficulty
Importance

The problem

A program needs to remember values across steps of computation and give them names so later code can refer back to them — without a name-to-value binding that can change over time, nothing but a single expression could ever be computed.

Why now

Types and values give us things worth remembering, but nothing yet lets us name a value or change what a name refers to as computation proceeds. Variables are the missing binding mechanism — and 'state' is what you get once that binding is allowed to change.

Mental model

A variable is a labeled box: the label (name) stays fixed while assignment can swap out what's inside. 'State' is just the total contents of all the boxes at a given moment — which is why two runs of the same program with different starting box-contents can behave completely differently.

Requires

Unlocks

Parallel

Used in

Projects

  • Trace a small program by hand, writing out the full variable-state table after every line executes
  • Convert a piece of code using mutable variables into an equivalent version using only immutable bindings, and compare readability

Examples

  • let count = 0; count = count + 1; — the name 'count' stays fixed, its bound value changes from 0 to 1
  • A debugger's 'variables' panel is literally a live view of current state

Resources

Mastery checklist