beginner · 26 minute study
Model allowed changes, not just stored fields
Both a game and an order workflow need to know which actions are valid now. Explicit transitions make invalid combinations harder to create.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Choose a data shape and follow the work it creates — Understand arrays, keyed lookups, uniqueness, algorithms and recursion well enough to recognize unnecessary work before optimizing blindly.
First, build a mental model
State is the information needed to decide what happens next. A transition maps the current state and an event to a next state. An invariant is a rule that must survive every accepted transition.
- A state machine names meaningful states such as ready, playing and paused, then limits which events apply to each.
- Validate an event before changing state so a rejected action cannot leave a half-updated object.
- Derived values should be computed from their source when practical instead of maintained as conflicting copies.
- An immutable update creates a new state value while preserving the old snapshot; it does not automatically freeze all nested data.
- Presentation controls can guide a user, but an authoritative transition must still reject an invalid direct request.
function spendEnergy(state, cost) {
if (state.phase !== 'playing' || cost < 1 || state.energy < cost) return state;
return { ...state, energy: state.energy - cost };
}
const before = { phase: 'paused', energy: 5 };
const after = spendEnergy(before, 2);
console.log(after.energy);- Current state
The game is paused with five energy units.
- Requested event
Spending two units is rejected because the phase is not playing.
- Invariant
The state remains unchanged, including its energy value of five.
Production thinking
Take this beyond the example.
Name the owner of each state transition. Use pure transition tests for local behavior and stronger integration tests for the authority that commits shared data.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Turn a failure into a controlled experiment →