How it works
The listener list is the whole design. Two decisions in it are worth explaining in an interview.
Copy-on-write. on and off build a new array and swap it into the map; nothing ever mutates an array that emit might be iterating. The cost moves to subscription time (O(n) per on/off), and emit allocates nothing. The alternative is to mutate in place and have emit copy the list ([...list]) on every call, which is cheaper when emits are rare and listeners change often. Both produce the same behaviour.
The once wrapper. The wrapper removes itself before calling the listener, so a listener that emits the same event again doesn't re-enter itself. Storing the original on wrapper.listener is what lets off(event, original) match. Node.js's own once wrappers keep the original on a listener property too; its docs show it through rawListeners().
Observer versus pub/sub is a question of where the list lives. In observer it lives in the subject; in pub/sub it lives in the broker, keyed by topic. A topic broker is just this emitter with a shared instance, which is why both patterns are implemented with the same code and differ in who can see whom.
Edge cases
Removing a listener during an emit. Implementations disagree on whether a listener removed mid-emit still runs:
import { EventEmitter } from 'node:events';
// Emitter is the class from the Example
const ours = new Emitter();
const node = new EventEmitter();
const target = new EventTarget(); // Node.js's implementation of the DOM interface
const log = [];
const second = () => log.push('second');
ours.on('x', () => ours.off('x', second));
ours.on('x', second);
node.on('x', () => node.off('x', second));
node.on('x', second);
target.addEventListener('x', () => target.removeEventListener('x', second));
target.addEventListener('x', second);
ours.emit('x');
node.emit('x');
target.dispatchEvent(new Event('x'));
console.log(log); // → [ 'second', 'second' ]
Only two entries: the Example's emitter and Node.js's EventEmitter still call second, while EventTarget doesn't. Node.js's docs say every listener attached at the moment of emitting is called, so removals take effect from the next emit. The DOM spec clones the list too, but its "remove an event listener" step sets a removed flag, and the inner invoke loop skips listeners with that flag. Neither is wrong; pick one and document it.
A throwing listener. In the Example and in Node.js's EventEmitter, an exception propagates out of emit and later listeners don't run. The DOM's inner invoke instead reports the exception and continues; Node.js's EventTarget follows that and treats the error as an uncaught exception on the next tick. If you want isolation in your own emitter, collect errors and rethrow them together:
function emitIsolated(listeners, ...args) {
const errors = [];
for (const listener of listeners) {
try {
listener(...args);
} catch (error) {
errors.push(error);
}
}
if (errors.length > 0) throw new AggregateError(errors, 'listener failed');
}
try {
emitIsolated([() => { throw new TypeError('bad'); }, () => console.log('second ran')]);
} catch (error) {
console.log(error.name, error.errors.length);
}
// → second ran
// → AggregateError 1
The 'error' event in Node.js. If nothing listens, emit('error', err) throws err itself. This is specific to EventEmitter; the Example's emitter treats 'error' like any other name unless you add the rule.
Real-world scenario
A UI component subscribes to an app-wide store or bus when it mounts and forgets to unsubscribe when it unmounts. Every mount adds a listener; each listener's closure holds the component's state and often its DOM nodes, so unmounted screens stay reachable through the bus. The fix is structural: make on return the unsubscribe function and call it from the component's cleanup, or use an AbortSignal with addEventListener.
Node.js has a tripwire for this. By default it warns once more than 10 listeners are added for one event on one emitter; its docs describe this as a hint for finding leaks, not a hard limit:
import { EventEmitter } from 'node:events';
process.on('warning', (warning) => console.log(warning.name));
const emitter = new EventEmitter();
for (let i = 0; i < 11; i++) emitter.on('data', () => {});
console.log(emitter.listenerCount('data')); // → 11
// → MaxListenersExceededWarning
The warning arrives after the synchronous code finishes, and Node.js also prints it to stderr. Raising the limit with setMaxListeners is right only when many listeners are legitimate.
Trade-offs
Events decouple the sender from its receivers, which is the point and also the cost: "who reacts to this?" is no longer answerable by reading the call site. Pub/sub decouples further, so a typo in a topic name fails silently. Prefer a direct call or an observer owned by the subject when there's one known receiver; reach for a bus when receivers genuinely come and go. Synchronous delivery keeps ordering and stack traces; asynchronous delivery protects the emitter from slow or throwing listeners at the cost of both.