Finite State Machines in JavaScript

By Dave Bitter

4 min read

Application state can make any application complex real quick. Let’s have a look at Finite State Machines in Javascript to resolve some of these complexities.

_Finite State Machines_ in JavaScript
Authors

Finite State Machines (FSMs) are a concept in programming that helps model complex systems with a fixed set of states and transitions between those states. In JavaScript, FSMs offer a structured approach to managing application logic for making code more organised, easier to maintain and more.

What is a Finite State Machine?

An FSM is a model that consists of three main components:

  • States: the distinct stages or conditions an application can be in at any given moment
  • Transitions: the description of how the FSM moves from one stage to the other
  • Events: the triggers for a transition of state

Example of an FSM

Let’s have a look at an example to make this concept more practical. Imagine an e-commerce website that tracks the status of a user's order. The order can be in various states, such as "Pending", "Processing", "Shipped" and "Delivered". The system is designed without using an FSM, relying on complex nested if-else statements to handle state transitions:

let orderStatus = 'Pending'

const updateOrderStatus = (event) => {
  if (orderStatus === 'Pending' && event === 'ProcessOrder') {
    orderStatus = 'Processing'
  } else if (orderStatus === 'Processing' && event === 'ShipOrder') {
    orderStatus = 'Shipped'
  } else if (orderStatus === 'Shipped' && event === 'DeliverOrder') {
    orderStatus = 'Delivered'
  } else {
    console.log('Invalid state transition or event.')
  }
}

Usually this is the moment I get a coffee to start figuring out what the business logic is in this function. As the codebase grows, more state transitions are added, leading to a convoluted and error-prone updateOrderStatus function. The lack of structure and clear separation between states and transitions make it challenging to maintain, debug, and extend the code.

By using an FSM, we can significantly improve the code's clarity and maintainability. Let's see how the same order status functionality can be implemented with an FSM:

const states = {
  PENDING: 'Pending',
  PROCESSING: 'Processing',
  SHIPPED: 'Shipped',
  DELIVERED: 'Delivered',
};

const transitions = {
  ProcessOrder: {
    [states.PENDING]: states.PROCESSING,
  },
  ShipOrder: {
    [states.PROCESSING]: states.SHIPPED,
  },
  DeliverOrder: {
    [states.SHIPPED]: states.DELIVERED,
  },
};

let orderStatus = states.PENDING;

const function updateOrderStatus => (event) {
  const nextState = transitions[event][orderStatus];

  if (nextState) {
    orderStatus = nextState;
  } else {
    console.log('Invalid state transition or event.');
  }
}

With the FSM implementation, the code becomes more structured and organised. When calling the updateOrderStatus function with "ProcessOrder" event, the state can only go to "Processing" if the current state is "Pending". This is the same business logic as before, but states and transitions are clearly defined, making it easier to understand the system's behaviour.

Flow chart representing the transitions mentioned above

As the number of states and transitions increases, the code remains clean and maintainable. For example, if you want to add a cancelled order state, you simply update the states and transitions objects:

const states = {
  PENDING: 'Pending',
  PROCESSING: 'Processing',
  SHIPPED: 'Shipped',
  DELIVERED: 'Delivered',
  CANCELLED: 'Cancelled',
};

const transitions = {
  ProcessOrder: {
    [states.PENDING]: states.PROCESSING,
  },
  ShipOrder: {
    [states.PROCESSING]: states.SHIPPED,
  },
  DeliverOrder: {
    [states.SHIPPED]: states.DELIVERED,
  },
  CancelOrder: {
    [states.PENDING]: states.CANCELLED,
    [states.PROCESSING]: states.CANCELLED,
  }
};

let orderStatus = states.PENDING;

const function updateOrderStatus => (event) {
  const nextState = transitions[event][orderStatus];

  if (nextState) {
    orderStatus = nextState;
  } else {
    console.log('Invalid state transition or event.');
  }
}

As you might notice, for the CancelOrder transition the state can only be cancelled if the order was in the “Pending” or “Processing” state. Other wise the user can’t cancel and as there is no transition implemented and you can handle your logic accordingly.

Benefits of Using Finite State Machines in JavaScript:

  • Clarity and Organization: FSMs provide a clear and organised representation of application logic. By breaking down complex behaviour into states and transitions, FSMs make the codebase more comprehensible and easier to follow. This clarity ensures that developers, both new and experienced, can understand the system's behaviour without diving into intricate details.
  • Modularity and Reusability: FSMs encourage modularity by compartmentalising states and transitions. Each state represents a well-defined portion of functionality, making it easy to reuse and combine states across different parts of the application. This modular approach reduces code duplication and allows developers to build applications with more flexibility.
  • Predictable Behavior: FSMs enable predictable behaviour in an application. Since each state and transition is explicitly defined, the system's responses to events become consistent and deterministic. Predictable behaviour is crucial for building robust and reliable applications, as it reduces the likelihood of unexpected bugs and unpredictable user experiences.
  • Easy Debugging and Testing: With FSMs, debugging and testing become more straightforward. The structured representation of states and transitions simplifies the process of identifying potential issues and bugs. Additionally, writing test cases for FSMs becomes more manageable, as each state can be tested independently, verifying that the system behaves correctly in different scenarios.
  • State Management: FSMs provide a systematic way to manage the application's state changes. As the system evolves, FSMs help developers maintain a clear overview of the states and their relationships. This structured state management contributes to better code maintainability, scalability, and overall code quality.

Finite State Machines offer a structured and organised approach to managing stateful behaviour in JavaScript applications. The benefits of FSMs, including clarity, modularity, predictability, easy debugging, and better state management, make them a valuable tool for simplifying complex systems and enhancing code quality. By embracing Finite State Machines, developers can avoid the issues that arise from poorly managed application logic and build more robust and maintainable JavaScript applications.


Upcoming events

  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🙋‍♀️ drinks 21:00 – 🍻 See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup

Share