Course contentsShow
← JavaScript
Lesson 2430 of 2,72349. Common Patterns and IdiomsFree lesson

Guarded Transitions

Introduce conditional logic to allow or block transitions based on runtime checks or context.

Guarded Transitions

What you'll learn: How to add conditional logic to finite-state machine transitions so they only occur when specific runtime conditions are met.

What Are Guarded Transitions?

In finite-state machines, not every event should always trigger a transition. A guard is a boolean condition that checks whether a transition should proceed. If the guard evaluates to false, the transition is blocked and the machine stays in its current state.

Think of a guarded transition like a bouncer at a club—the event is your ticket, but the bouncer (guard) checks your ID. Even with a ticket, you might not get in if you don't meet the conditions.

How It Works

When an event occurs, your FSM evaluates the guard function before changing state. Only if the guard returns true does the transition happen.

const machine = {
  state: 'idle',
  context: { credits: 0 },

  transitions: {
    idle: {
      INSERT_COIN: {
        target: 'ready',
        guard: (context) => context.credits >= 1
      }
    },
    ready: {
      START: { target: 'running' }
    }
  }
};

function send(event) {
  const transition = machine.transitions[machine.state]?.[event];
  
  if (transition && (!transition.guard || transition.guard(machine.context))) {
    machine.state = transition.target;
    console.log(`Transitioned to ${machine.state}`);
  } else {
    console.log('Transition blocked by guard');
  }
}

send('INSERT_COIN'); // "Transition blocked by guard" (0 credits)
machine.context.credits = 1;
send('INSERT_COIN'); // "Transitioned to ready" (guard passed)

Why Use Guards?

Guards prevent invalid state transitions based on business logic, user permissions, validation results, or any runtime context. They keep your FSM flexible and accurate to real-world conditions.

Key Takeaway: Guarded transitions use boolean conditions to allow or deny state changes, ensuring your FSM only transitions when the runtime context satisfies specific requirements.