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

  • Drupal CMS Launch Party

    Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u – 18u30: Drupal CMS livestream met taart 18u30 – 19u00: Versteld staan van de functionaliteiten 19u – 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!

    | Coven of Wisdom Herentals

    Go to page for Drupal CMS Launch Party
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele 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 – 📢 Building a Mature Digital Ecosystem - Maarten Heip 20:00 – 🍹 Kleine pauze 20:15 – 📢 Compound Components: A Better Way to Build React Components - Sead Memic 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creëren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. 📍 Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. 🎫 Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! 😋 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
  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 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: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup

Share