Home
← All questions

Implement the pub/sub pattern in JavaScript

MediumPremiumJavaScript

JavaScript interview practice: Build a publish/subscribe event bus with subscribe, publish, and unsubscribe.

Problem

Decoupled widgets, micro-frontends and cross-tab messaging often communicate through an event bus, and being able to implement the pub/sub pattern in JavaScript is a common frontend interview question.

Implement a class PubSub with:

  • subscribe(event, callback) registers callback for event and returns a handle object with an unsubscribe() method.
  • publish(event, ...args) invokes every callback currently subscribed to event with args.

Requirements

  • Any number of subscribers can listen to the same event; publish calls all of them, in subscription order.
  • Every argument passed to publish after the event name is forwarded to each callback.
  • unsubscribe() removes only the subscription it was returned for; other subscribers keep working.
  • Calling unsubscribe() more than once must not throw.
  • Publishing an event with no subscribers is a silent no-op.
  • Events are independent: publishing "login" never triggers "logout" subscribers.

Example

const bus = new PubSub();

const s1 = bus.subscribe("cart:add", (item, qty) => console.log("s1", item, qty));
bus.subscribe("cart:add", (item) => console.log("s2", item));

bus.publish("cart:add", "book", 2);
// s1 book 2
// s2 book

s1.unsubscribe();
s1.unsubscribe(); // no error
bus.publish("cart:add", "pen", 1);
// s2 pen

bus.publish("cart:clear"); // (nothing logged)

Follow-ups

  • How would you support wildcard subscriptions such as "cart:*"?
  • How would you prevent one throwing subscriber from stopping the others?
  • How does this differ from the observer pattern?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium