An observer keeps a list of listeners per event and calls them when the event happens: on adds, off removes, emit calls each with the arguments. The follow-ups are what make it production code: on returning an unsubscribe function, once, iterating over a snapshot so listeners that remove themselves (or add others) during an emit don't break the loop, and not letting one throwing listener silence the rest. The advanced form is an observable store (getState, setState, subscribe), which is the contract React's useSyncExternalStore expects.
Observer pattern
The best way to prepare for JavaScript coding questions is to get your hands dirty by implementing them yourself and writing test cases for them.
Although the focus of such questions is not on algorithms, do pay attention to choice of data structures and the time complexity as well. Don't write a function that runs in O(n<sup>2</sup>) if it can pretty easily have an O(n) runtime with the use of hash maps.
Candidates are expected to take just around 10-15 minutes for a basic question. If you can tell that you received a basic question, try to finish within the suggested duration and do not intentionally take the entire interview to do one question. In most cases, you are expected to answer another coding question.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
A Map from event name to an array of listeners. emit calls each with apply(this, args) and, like Node's EventEmitter, returns whether anyone was listening. off filters the listener out.
class EventEmitter {#listeners = new Map(); // event name -> array of listenerson(name, listener) {if (!this.#listeners.has(name)) this.#listeners.set(name, []);this.#listeners.get(name).push(listener);return this;}off(name, listener) {const list = this.#listeners.get(name);if (list) this.#listeners.set(name, list.filter((l) => l !== listener));return this;}emit(name, ...args) {const list = this.#listeners.get(name) ?? [];for (const listener of list) listener.apply(this, args);return list.length > 0; // like Node: did anyone listen?}}
passes 3 checks run on every build, against the native method where there is one
- every listener hears the event with its arguments
- off removes a listener
- emitting with no listeners returns false
Returning an unsubscribe function from on means callers don't have to keep a reference to the listener (React effects return it as their cleanup). once removes itself before running. Lists are replaced, never mutated, so emit loops over a snapshot: a listener that removes itself doesn't make the loop skip the next one, and one added mid-emit hears the next event. Errors are collected and thrown after every listener has run (Node's EventEmitter stops at the first throw instead; say which you chose and why).
class EventEmitter {#listeners = new Map();// Returns a function that unsubscribes: no need to keep the listener around to remove it.on(name, listener) {if (typeof listener !== 'function') throw new TypeError('listener must be a function');const list = this.#listeners.get(name) ?? [];this.#listeners.set(name, [...list, { listener, once: false }]);return () => this.off(name, listener);}once(name, listener) {const list = this.#listeners.get(name) ?? [];this.#listeners.set(name, [...list, { listener, once: true }]);return () => this.off(name, listener);}// Removes one registration (the most recent), like Node.off(name, listener) {const list = this.#listeners.get(name);if (!list) return;const i = list.findLastIndex((entry) => entry.listener === listener);if (i === -1) return;const next = list.toSpliced(i, 1);if (next.length) this.#listeners.set(name, next);else this.#listeners.delete(name);}emit(name, ...args) {// A snapshot: listeners added or removed during this emit don't change who hears it.const list = this.#listeners.get(name) ?? [];const errors = [];for (const entry of list) {if (entry.once) this.off(name, entry.listener);try {entry.listener.apply(this, args);} catch (err) {errors.push(err); // one broken listener must not silence the rest}}if (errors.length === 1) throw errors[0];if (errors.length > 1) throw new AggregateError(errors, `${errors.length} listeners of "${String(name)}" threw`);return list.length > 0;}listenerCount(name) {return this.#listeners.get(name)?.length ?? 0;}}
passes 7 checks run on every build, against the native method where there is one
- on returns an unsubscribe function
- once runs once
- a once listener can be removed before it fires
- removing a listener during emit doesn't skip the next one
- a listener added during emit waits for the next emit
- one throwing listener doesn't stop the others, and the error still surfaces
- the same listener twice is two registrations
The same pattern with one piece of state: subscribe returns an unsubscribe, setState notifies only when the value actually changes (Object.is), and listeners are copied before the loop. A listener that calls setState doesn't recurse: the change is noted and everyone is notified again once the current round ends, so all listeners see the final state. select narrows a subscription to one slice, which is how stores avoid re-rendering everything on every change.
// An observable store: the same pattern React's useSyncExternalStore expects.function createStore(initial) {let state = initial;const listeners = new Set();let depth = 0; // nested setState calls inside a listenerlet pending = false;const notify = () => {// Copy first: a listener may unsubscribe itself or others while we loop.for (const listener of [...listeners]) if (listeners.has(listener)) listener(state);};return {getState: () => state,setState(update) {const next = typeof update === 'function' ? update(state) : update;if (Object.is(next, state)) return; // no change, no notificationstate = next;if (depth > 0) {pending = true; // a listener changed state: tell everyone once more afterwardsreturn;}depth++;try {do {pending = false;notify();} while (pending);} finally {depth--;}},subscribe(listener) {listeners.add(listener);return () => listeners.delete(listener);},// Listen to one slice; fires only when that slice changes.select(selector, listener, isEqual = Object.is) {let current = selector(state);return this.subscribe((s) => {const next = selector(s);if (isEqual(next, current)) return;const previous = current;current = next;listener(next, previous);});},};}
passes 4 checks run on every build, against the native method where there is one
- subscribers hear changes, not no-op updates
- unsubscribing during a notification is safe
- a listener that sets state doesn't recurse; everyone sees the final state
- select fires only when its slice changes
External stores in React
useSyncExternalStore(subscribe, getSnapshot) lets any store drive React: it calls subscribe with a listener, expects an unsubscribe back, and re-reads getSnapshot when notified. Redux, Zustand and browser APIs plug in this way.
The DOM is an observer
addEventListener and removeEventListener are the same pattern, with { once: true } and { signal } options; aborting the signal removes every listener added with it, which replaces keeping references for cleanup.
Listener leaks
Forgetting to unsubscribe keeps every listener (and what it closes over) alive. Node warns after 10 listeners on one event (MaxListenersExceededWarning) because that usually means a leak.
Looping over the live listener array while listeners remove themselves: the next listener is skipped.
No way to unsubscribe, or unsubscribing in the wrong React effect, so listeners pile up on every render.
onceimplemented with a wrapper function, and thenoff(name, original)can't find it.Notifying on every
setStateeven when nothing changed, which re-renders everything.A listener that calls
setStatecausing unbounded recursion.
How is this different from pub/sub?
In the observer pattern subjects hold their observers directly. In pub/sub, publishers and subscribers only know a channel or broker in between (a message bus, BroadcastChannel), so either side can come and go independently.
Should emit call listeners synchronously?
The DOM and Node do, so state is consistent right after emit returns. Calling them asynchronously (in a microtask) avoids re-entrancy surprises but means listeners may see newer state than the event described. Pick one and document it.
How do you avoid memory leaks with many short-lived listeners?
Return unsubscribe functions and call them in cleanup, or pass an AbortSignal and abort it once. For caches keyed by objects, a WeakMap lets entries disappear with their keys.
- nodejs.org/api/events.html
- developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
- react.dev/reference/react/useSyncExternalStore
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError