The three stages map onto the steps below. Stage 1: on, off and emit over a Map of listener lists, with emit returning whether anyone listened. Stage 2: once, an unsubscribe function returned from on, and safe emitting: loop over a copy so listeners can add or remove others mid-emit, and remove a once listener before calling it. Stage 3 is where senior candidates separate themselves: AbortSignal removal, an unhandled 'error' that throws (Node's rule), and next(name) returning a cancellable promise for the next emit. Name the trade-offs as you go: synchronous emit, and whether one throwing listener should stop the rest.
Implement an event emitter progressively in 3 stages of increasing complexity. Senior / staff candidates are expected to clear all 3 stages.
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. on appends and returns this for chaining. emit calls each listener with the arguments, with this set to the emitter, and returns whether anyone was listening. off removes one registration of the function: the most recent one, which is what Node does when the same function was added twice. A Map rather than a plain object means event names like __proto__ or constructor can't collide with inherited properties.
class EventEmitter {#listeners = new Map(); // event name -> listener functions, in the order addedon(name, fn) {if (!this.#listeners.has(name)) this.#listeners.set(name, []);this.#listeners.get(name).push(fn);return this; // chainable, like Node's emitter}off(name, fn) {const list = this.#listeners.get(name);if (!list) return this;const i = list.lastIndexOf(fn); // one registration, the most recent, as Node doesif (i !== -1) list.splice(i, 1);return this;}emit(name, ...args) {const list = this.#listeners.get(name);if (!list || list.length === 0) return false;for (const fn of list) fn.apply(this, args);return true; // whether anyone was listening}}
passes 4 checks run on every build, against the native method where there is one
- listeners get the arguments, in the order added
- emit with no listeners returns false
- off removes one registration
- events are separate; this is the emitter
on now returns an unsubscribe function, so callers don't have to keep a reference to their listener (the pattern most UI code wants). Listeners are stored as entries, so once can mark one and off can still find it by the original function. emit loops over a copy, so a listener that removes another, or adds a new one, doesn't change the emit in progress, which matches Node's documented behaviour. A once entry is removed before it's called, so emitting the same event from inside it can't call it again. Empty arrays are deleted, so names don't pile up.
class EventEmitter {#listeners = new Map(); // name -> [{ fn, once }]// Returns an unsubscribe function: the caller doesn't need to keep the listener around.on(name, fn) {return this.#add(name, { fn, once: false });}once(name, fn) {return this.#add(name, { fn, once: true });}off(name, fn) {const list = this.#listeners.get(name) ?? [];for (let i = list.length - 1; i >= 0; i--) {if (list[i].fn === fn) { // also finds listeners added with once()this.#remove(name, list[i]);break;}}return this;}emit(name, ...args) {const list = this.#listeners.get(name);if (!list || list.length === 0) return false;// Iterate over a copy: listeners added or removed while emitting don't change this emit.for (const entry of [...list]) {if (entry.once) this.#remove(name, entry); // before the call, so a nested emit can't call it twiceentry.fn.apply(this, args);}return true;}#add(name, entry) {if (typeof entry.fn !== 'function') throw new TypeError('listener must be a function');if (!this.#listeners.has(name)) this.#listeners.set(name, []);this.#listeners.get(name).push(entry);return () => this.#remove(name, entry);}#remove(name, entry) {const list = this.#listeners.get(name);const i = list ? list.indexOf(entry) : -1;if (i !== -1) list.splice(i, 1);if (list && list.length === 0) this.#listeners.delete(name); // no empty arrays left behind}}
passes 6 checks run on every build, against the native method where there is one
- on returns an unsubscribe function
- once fires a single time, even if emitted from inside itself
- removing a listener during emit doesn't affect that emit
- adding a listener during emit waits for the next emit
- off finds a once listener by its function
- non-functions are rejected
Three things senior candidates add. An AbortSignal option removes listeners in bulk, the way addEventListener does, which makes component cleanup one abort(). An 'error' event with no listener throws instead of disappearing, which is Node's rule. And next(name) returns a promise for the next emit's arguments, cancellable with a signal and leaving no listener behind, like Node's events.once(). Listener errors still propagate out of emit and stop the remaining listeners. Say so, and offer to catch and rethrow after the loop if every listener must run.
class EventEmitter {#listeners = new Map();// { signal } removes the listener when the signal aborts, like addEventListener.on(name, fn, { once = false, signal } = {}) {if (typeof fn !== 'function') throw new TypeError('listener must be a function');if (signal?.aborted) return () => {};const entry = { fn, once };if (!this.#listeners.has(name)) this.#listeners.set(name, []);this.#listeners.get(name).push(entry);const off = () => {this.#remove(name, entry);signal?.removeEventListener('abort', off);};signal?.addEventListener('abort', off, { once: true });return off;}once(name, fn, options) {return this.on(name, fn, { ...options, once: true });}off(name, fn) {const list = this.#listeners.get(name) ?? [];for (let i = list.length - 1; i >= 0; i--) {if (list[i].fn === fn) {this.#remove(name, list[i]);break;}}return this;}emit(name, ...args) {const list = this.#listeners.get(name);if (!list || list.length === 0) {// Node's rule: an 'error' nobody handles is thrown, never silently dropped.if (name === 'error') throw args[0] instanceof Error ? args[0] : new Error(`Unhandled error: ${String(args[0])}`);return false;}for (const entry of [...list]) {if (entry.once) this.#remove(name, entry);entry.fn.apply(this, args);}return true;}listenerCount(name) {return this.#listeners.get(name)?.length ?? 0;}// A promise for the next emit's arguments, like Node's events.once(); cancellable.next(name, { signal } = {}) {return new Promise((resolve, reject) => {if (signal?.aborted) return reject(signal.reason);const onAbort = () => {off();reject(signal.reason);};const off = this.once(name, (...args) => {signal?.removeEventListener('abort', onAbort);resolve(args);});signal?.addEventListener('abort', onAbort, { once: true });});}#remove(name, entry) {const list = this.#listeners.get(name);const i = list ? list.indexOf(entry) : -1;if (i !== -1) list.splice(i, 1);if (list && list.length === 0) this.#listeners.delete(name);}}
passes 5 checks run on every build, against the native method where there is one
- an AbortSignal removes listeners
- an unhandled 'error' event throws
- next() resolves with the next emit's arguments
- next() can be cancelled and leaves nothing behind
- once and the copy-on-emit rules still hold
Node's EventEmitter
Streams, servers and child processes are all emitters. The rules above (copy during emit, once removed before the call, unhandled 'error' throws) come from Node's documentation.
EventTarget in the browser
The DOM's addEventListener uses the same idea with options: once, and signal to remove a listener when an AbortController aborts.
Leaks from forgotten listeners
A listener that's never removed keeps its closure alive. Node warns when one event gets more than 10 listeners because it is usually a leak.
Iterating over the live array during
emit, so anoffinside a listener skips the next listener.Implementing
oncewith a wrapper but thenoff(name, originalFn)can't find it.Removing a
oncelistener after calling it, so a nested emit calls it twice.A plain object keyed by event name, where
'constructor'or'__proto__'misbehave.Never removing listeners in components, which leaks memory and runs handlers for unmounted UI.
Should one throwing listener stop the others?
Node lets the error propagate and stops. If every listener must run, catch each error, keep going, and rethrow at the end (or an AggregateError when there were several).
Synchronous or asynchronous emit?
Synchronous, like Node and the DOM: listeners run before emit returns, which keeps ordering predictable. Make listeners defer their own work with queueMicrotask if needed.
How would you type it in TypeScript?
Make the class generic over an event map, EventEmitter<{ data: [chunk: string]; end: [] }>, so on('data', fn) checks the listener's parameters against the map.