Variables & State
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
- Types & ValuesProgramming Fundamentals
A variable is a name bound to a value of some type; without a notion of value and type there is nothing for the name to refer to.
Unlocks
Parallel
Used in
- Every imperative programming language's assignment statement (x = 5)
- React/Redux state management (component state is named, mutable bindings)
- Database rows (a record's fields are named, updatable bindings)
- Configuration and environment variables in deployed systems
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
- I can explain the difference between a variable's name and its bound value
- I can define 'program state' precisely as the set of current variable bindings
- I can trace a short program by hand and produce a correct state table
- I can explain why immutable bindings eliminate a category of bugs related to unexpected state change