The State Pattern in JavaScript, With Real Examples
The state pattern lets an object change its behavior when its state changes by delegating to state objects. See an order and a media player in JavaScript.

The state pattern lets an object change its behavior when its internal state changes, by delegating to a separate object for each state. The object seems to change its class at runtime. It is the object-oriented answer to code full of if (this.status === "paid") checks repeated in every method. Instead of one class with a status flag and conditionals in each method, you write one small class per state, each knowing only what is allowed in that state, and the main object forwards calls to the current one. It is closely related to the state machine approach, which puts the transitions in a table, while the pattern puts behavior in classes. This post builds an order workflow in JavaScript on Node.js 24 with the pattern, a media player, a TypeScript version, and covers when a table or a switch is the better tool. Every sample prints its output.
The problem: conditionals in every method
An order can be placed, paid, shipped or cancelled, and each action is valid only in some states.
class Order {
status = "placed";
pay() {
if (this.status === "placed") this.status = "paid";
else throw new Error(`Cannot pay an order that is ${this.status}`);
}
ship() {
if (this.status === "paid") this.status = "shipped";
else throw new Error(`Cannot ship an order that is ${this.status}`);
}
cancel() {
if (this.status === "placed" || this.status === "paid") this.status = "cancelled";
else throw new Error(`Cannot cancel an order that is ${this.status}`);
}
}
const order = new Order();
order.pay();
order.ship();
try {
order.cancel();
} catch (err) {
console.log(err.message);
}
console.log(order.status);Cannot cancel an order that is shipped
shippedIt works, and the structure is a grid: every method repeats a check against the same list of states. Add a refunded state, and you must find every method and decide how it should behave there. The rules for one state, such as everything you can do to a shipped order, are scattered across all the methods.
One class per state
Give each state its own class that implements the same methods. The context, the order, holds the current state and delegates.
class PlacedState {
pay(order) {
order.transitionTo(new PaidState());
}
ship() {
throw new Error("Cannot ship an unpaid order");
}
cancel(order) {
order.transitionTo(new CancelledState());
}
get name() {
return "placed";
}
}
class PaidState {
pay() {
throw new Error("Order is already paid");
}
ship(order) {
order.transitionTo(new ShippedState());
}
cancel(order) {
order.transitionTo(new CancelledState());
}
get name() {
return "paid";
}
}
class ShippedState {
pay() {
throw new Error("Order is already paid");
}
ship() {
throw new Error("Order is already shipped");
}
cancel() {
throw new Error("Cannot cancel a shipped order");
}
get name() {
return "shipped";
}
}
class CancelledState {
pay() {
throw new Error("Order is cancelled");
}
ship() {
throw new Error("Order is cancelled");
}
cancel() {
throw new Error("Order is already cancelled");
}
get name() {
return "cancelled";
}
}
export class Order {
#state = new PlacedState();
history = ["placed"];
transitionTo(state) {
this.#state = state;
this.history.push(state.name);
}
pay() {
this.#state.pay(this);
}
ship() {
this.#state.ship(this);
}
cancel() {
this.#state.cancel(this);
}
get status() {
return this.#state.name;
}
}
const order = new Order();
order.pay();
order.ship();
console.log(order.status, order.history);
try {
order.cancel();
} catch (err) {
console.log(err.message);
}
const early = new Order();
early.cancel();
try {
early.pay();
} catch (err) {
console.log(err.message);
}shipped [ 'placed', 'paid', 'shipped' ]
Cannot cancel a shipped order
Order is cancelledEverything about a shipped order lives in ShippedState. The Order class has no conditionals at all: each method forwards to the current state, and the state may ask the context to switch with transitionTo. Adding RefundedState means writing one class and changing the transitions that lead to it, and no other state's code. The transition rules are also now data in the code that creates the next state, which is easy to read in one place.
Shared behavior with a base class
The repeated throw lines suggest a base class with defaults that states override. Every state starts out refusing everything, and each subclass allows only what it should.
class OrderState {
pay() {
throw new Error(`Cannot pay: order is ${this.name}`);
}
ship() {
throw new Error(`Cannot ship: order is ${this.name}`);
}
cancel() {
throw new Error(`Cannot cancel: order is ${this.name}`);
}
}
class Placed extends OrderState {
name = "placed";
pay(order) {
order.transitionTo(new Paid());
}
cancel(order) {
order.transitionTo(new Cancelled());
}
}
class Paid extends OrderState {
name = "paid";
ship(order) {
order.transitionTo(new Shipped());
}
cancel(order) {
order.transitionTo(new Cancelled());
}
}
class Shipped extends OrderState {
name = "shipped";
}
class Cancelled extends OrderState {
name = "cancelled";
}
const order = { state: new Placed(), transitionTo(s) { this.state = s; } };
order.state.pay(order);
console.log(order.state.name);
try {
order.state.pay(order);
} catch (err) {
console.log(err.message);
}
order.state.ship(order);
try {
order.state.cancel(order);
} catch (err) {
console.log(err.message);
}paid
Cannot pay: order is paid
Cannot cancel: order is shippedThe terminal states Shipped and Cancelled are two lines each, since they inherit refusal for every action. This reads as an allow list per state, which is safer than a deny list: a new action added to the base class is forbidden everywhere until a state opts in.
A media player
The pattern fits interactive controls, where the same button does different things in different states.
class Player {
#state;
constructor() {
this.#state = new Stopped();
}
set(state) {
this.#state = state;
}
press() {
return this.#state.press(this);
}
stop() {
return this.#state.stop(this);
}
}
class Stopped {
press(player) {
player.set(new Playing());
return "start playing";
}
stop() {
return "already stopped";
}
}
class Playing {
press(player) {
player.set(new Paused());
return "pause";
}
stop(player) {
player.set(new Stopped());
return "stop";
}
}
class Paused {
press(player) {
player.set(new Playing());
return "resume";
}
stop(player) {
player.set(new Stopped());
return "stop";
}
}
const player = new Player();
console.log(player.press(), player.press(), player.press(), player.stop(), player.stop());start playing pause resume stop already stoppedThe single press() method means "play" when stopped, "pause" when playing and "resume" when paused. The interface code just calls press, and the state decides. Without the pattern, press would be a three-way switch that grows with every feature.
States that share data
Sometimes states need data from the context, such as the amount to refund. Pass the context in, as above, or give states a narrow interface. Avoid letting states reach into the context's fields freely, which couples them.
States can also be stateless singletons. In the examples each transition creates a new state object, which is fine for small ones. If states hold no data, create them once and reuse them.
const Placed = Object.freeze({ name: "placed", next: () => Paid });
const Paid = Object.freeze({ name: "paid", next: () => Shipped });
const Shipped = Object.freeze({ name: "shipped", next: () => null });
let state = Placed;
const path = [state.name];
while (state.next()) {
state = state.next();
path.push(state.name);
}
console.log(path.join(" -> "));placed -> paid -> shippedHere the states are plain frozen objects. The next thunks are lazy, so the constants can refer to each other even though Paid and Shipped are defined after Placed.
In TypeScript
Typed states make the interface explicit, so a new state that forgets a method fails to compile.
interface TrafficLightState {
readonly color: string;
next(): TrafficLightState;
}
class Red implements TrafficLightState {
readonly color = "red";
next() {
return new Green();
}
}
class Green implements TrafficLightState {
readonly color = "green";
next() {
return new Yellow();
}
}
class Yellow implements TrafficLightState {
readonly color = "yellow";
next() {
return new Red();
}
}
let light: TrafficLightState = new Red();
const seen: string[] = [light.color];
for (let i = 0; i < 4; i++) {
light = light.next();
seen.push(light.color);
}
console.log(seen.join(" "));red green yellow red greenState pattern versus state machine
The two address the same problem from different sides. A state machine, in the table form, keeps transitions as data and is easy to inspect, draw and test, but behavior sits outside it in handlers. The state pattern keeps behavior with the state in a class, which is easy to extend with state-specific logic and polymorphism, but the transition rules are spread across the classes. A rough guide: if the interesting part is the graph of allowed moves, use a table or XState. If each state has a lot of its own behavior, many methods that differ by state, use the pattern.
Pitfalls
State explosion. Every new state is a class, and every new action touches all of them. If you have twelve states and eight actions, that is ninety-six method bodies, mostly refusals. A base class with default refusal helps. Hierarchical states or a table are better beyond that.
Hidden transitions. When states call transitionTo, the full set of transitions appears only by reading all the classes. Document them in a diagram or a comment, and test them.
Persistence. To save an order, store the state's name and rebuild the object from a lookup table when loading. Do not try to serialize the class instance.
Shared mutable state in singletons. If you reuse state objects, they must hold no per-order data.
Where the advice stops
For two or three states with simple rules, a status string and a few conditionals are clearer. Adopt the pattern when you find the same list of if checks on the status in many methods, or when states carry meaningful behavior of their own. If all you need is validity of transitions, a transition table is shorter.
Testing the states
State classes test well because each one has a small, closed list of behaviors. For each state, write one test per action: either the transition it triggers, checked through the context's status, or the error it raises. A table of state, action and expected outcome covers the whole grid in a few lines, and it doubles as documentation of the allowed moves. Then add a test that walks the happy path from the first state to a terminal one, and one that tries an invalid action from every state to confirm nothing leaks through.
Moving between this pattern and a table
Both approaches can coexist. A common design keeps the transitions in a table for clarity and inspection, and uses state objects only for states with real behavior, such as one that starts a timer on entry and cancels it on exit. Entry and exit hooks are a natural place for the pattern: enter(context) and exit(context) methods let a state set up and tear down what it owns, so the context does not need to know. If you find you are writing the same transition logic in many state classes, that logic belongs in a table.


