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

Transition Functions and Event Handling

Write a transition function that takes the current state and an event, returning the next state.

Transition Functions and Event Handling

You'll learn how to implement a transition function that processes state changes in a finite-state machine by accepting the current state and an event, then computing the next state.

Core Concept

A transition function is the heart of a finite-state machine. It's a pure function that takes two inputs—the current state and an event (or action)—and returns the next state. Think of it as a decision-making blueprint: "Given where I am now and what just happened, where should I go next?"

This pattern keeps your state logic centralized, predictable, and testable. Instead of scattering state changes throughout your code, you consolidate all transition rules in one place.

Basic Structure

function transition(currentState, event) {
  // Return the next state based on current state + event
}

Simple Example

function trafficLightTransition(state, event) {
  if (state === 'red' && event === 'TIMER') {
    return 'green';
  }
  if (state === 'green' && event === 'TIMER') {
    return 'yellow';
  }
  if (state === 'yellow' && event === 'TIMER') {
    return 'red';
  }
  return state; // No valid transition, stay in current state
}

let currentState = 'red';
currentState = trafficLightTransition(currentState, 'TIMER'); // 'green'
currentState = trafficLightTransition(currentState, 'TIMER'); // 'yellow'

Using Objects for Complex Transitions

const transitions = {
  idle: { START: 'loading' },
  loading: { SUCCESS: 'ready', ERROR: 'error' },
  ready: { RESET: 'idle' },
  error: { RETRY: 'loading' }
};

function transition(state, event) {
  return transitions[state]?.[event] || state;
}

This object-based approach scales better with many states and events.

Key Takeaway: A transition function encapsulates all state-change logic in a single, predictable function that maps (currentState, event) → nextState, making your FSM explicit and maintainable.