Skip to content

Finite State Machine

Medium ~40 min

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. 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 }.

    Code
    const 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. 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.

    Code
    class StateMachine {
      constructor(initial, transitions) {
        this.state = initial;
        this.transitions = transitions;
        this.history = [initial];
      }
    }

    Expected result

    A StateMachine starting in the given initial state.

  3. 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.

  4. 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.

  5. 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.

    Code
    const 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')); // true

    Expected result

    Output shows transitions, history of 3 states, and canSend returns true.

Try it yourself

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

Related Lessons

  • Objects

    Nested objects encode the transition table.

  • Events

    send(event) is the FSM's event handler.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic