Finite State Machine
What you'll build
A StateMachine class that validates transitions against a defined state table, rejects invalid transitions, and calls actions on transition.
Goals
- Define states, events, and a transition table
- Validate transitions and reject invalid ones
- Execute actions (side effects) on transitions
- Track current state and history
Prerequisites
- Objects and Maps
- Functions as values
- if/else conditionals
Steps
- 1
Define the transition table
A FSM is defined by states, events, and which event moves from which state to which state. Encode this as a nested object: transitions[fromState][event] = { to, action }.
Codeconst turnstileTransitions = { locked: { coin: { to: 'unlocked', action: () => console.log('Unlocking') }, push: { to: 'locked', action: () => console.log('Still locked') }, }, unlocked: { coin: { to: 'unlocked', action: () => console.log('Already unlocked') }, push: { to: 'locked', action: () => console.log('Locking') }, }, };Expected result
A transition table for a coin-operated turnstile with locked/unlocked states.
- 2
Implement the StateMachine class
The class takes an initial state and a transition table. It stores the current state and exposes send(event) to trigger transitions.
Codeclass StateMachine { constructor(initial, transitions) { this.state = initial; this.transitions = transitions; this.history = [initial]; } }Expected result
A StateMachine starting in the given initial state.
- 3
Implement send with validation
send(event) looks up transitions[state][event]. If it doesn't exist, log a warning and return false (invalid transition). If it exists, run the action, update state, and push to history.
Hint
Use optional chaining: this.transitions[this.state]?.[event] to safely look up.
- 4
Add a canSend guard
Add canSend(event) that returns true if the transition exists without executing it. This lets UIs disable buttons for invalid actions.
Hint
It's the same lookup as send, but returns a boolean instead of executing.
- 5
Test the turnstile FSM
Create a turnstile starting 'locked'. Send coin (→unlocked), push (→locked), push (invalid from locked? no, push keeps it locked). Verify history and that invalid transitions are rejected.
Codeconst turnstile = new StateMachine('locked', turnstileTransitions); turnstile.send('coin'); // Unlocking, state: unlocked turnstile.send('push'); // Locking, state: locked console.log('History:', turnstile.history); // ['locked', 'unlocked', 'locked'] console.log('Can coin?', turnstile.canSend('coin')); // trueExpected result
Output shows transitions, history of 3 states, and canSend returns true.
Try it yourself
class StateMachine {
constructor(initial, transitions) { /* TODO */ }
send(event) { /* TODO */ }
canSend(event) { /* TODO */ }
}class StateMachine {
constructor(i, t) { this.state = i; this.transitions = t; this.history = [i]; }
send(e) { const tr = this.transitions[this.state]?.[e]; if (!tr) return false; tr.action?.(); this.state = tr.to; this.history.push(this.state); return true; }
canSend(e) { return !!this.transitions[this.state]?.[e]; }
}What you learned
You built a finite state machine — the formal model behind UI routing, game logic, parser states, and libraries like XState. FSMs make complex state transitions verifiable and bug-free.
Related Resources
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.