Modeling a Simple FSM with Objects
You'll learn how to represent a finite-state machine using a plain JavaScript object that maps each state to its valid transitions.
The Core Idea
Now that you understand FSM vocabulary (states and transitions), let's build one using simple objects. The most straightforward approach is creating an object where each key is a state name, and its value is another object mapping transition events to destination states.
Think of it like a "choose your own adventure" book: each page (state) lists what page numbers (states) you can jump to based on different choices (transitions).
Basic Structure
const fsm = {
idle: {
START: 'running',
STOP: 'idle' // staying in same state is valid
},
running: {
PAUSE: 'paused',
STOP: 'idle'
},
paused: {
RESUME: 'running',
STOP: 'idle'
}
};
Each property (idle, running, paused) represents a state. Each nested object defines which events trigger transitions to new states.
Using the FSM
let currentState = 'idle';
function transition(event) {
const nextState = fsm[currentState]?.[event];
if (nextState) {
console.log(`${currentState} → ${event} → ${nextState}`);
currentState = nextState;
} else {
console.log(`Invalid transition: ${event} from ${currentState}`);
}
}
transition('START'); // idle → START → running
transition('PAUSE'); // running → PAUSE → paused
transition('START'); // Invalid: can't START from paused
This simple object-based model gives you clear rules: if a transition exists in the mapping, it's allowed; otherwise, it's invalid.
Key Takeaway: A plain object can model an FSM by mapping each state to an object of valid event→nextState pairs, giving you a readable, declarative way to enforce state transition rules.