Course contentsShow
← JavaScript
Lesson 521 of 2,72313. ClosuresFree lesson

State Machines with Closures

Implement finite state machines where current state lives in closure and transitions are controlled.

State Machines with Closures

You'll learn how to build a finite state machine that keeps its current state private inside a closure and exposes transition methods.

What Is a State Machine?

A state machine is a pattern where something can be in exactly one state at a time (like "idle," "loading," or "error"), and can only transition between states in specific, controlled ways. Think of a turnstile at a subway: it's either locked or unlocked, and you can only transition between those states by inserting a coin or pushing through.

Building One with Closures

Closures are perfect for state machines because you can hide the current state in a private variable that only your transition functions can access. The outside world can't accidentally mess with the state—it can only trigger valid transitions.

function createTrafficLight() {
  let state = 'red';

  return {
    getState() {
      return state;
    },
    next() {
      if (state === 'red') state = 'green';
      else if (state === 'green') state = 'yellow';
      else if (state === 'yellow') state = 'red';
    }
  };
}

const light = createTrafficLight();
console.log(light.getState()); // "red"
light.next();
console.log(light.getState()); // "green"
light.next();
console.log(light.getState()); // "yellow"

The state variable lives in the closure—there's no light.state property anyone can accidentally overwrite. Each transition method checks the current state and updates it according to your rules.

Why This Works

The closure preserves state across multiple method calls, but keeps it completely private. You define exactly which transitions are allowed, preventing invalid state changes like jumping from red straight to yellow.

Key Takeaway: Closures let you build state machines with private state that can only change through controlled transition functions, ensuring your state logic stays predictable and protected.