← Back to JavaScript, page 5

javascript-0082 · Medium mid

Implement an EventEmitter class with on, once, off, and emit, and explain the edge cases.

An event emitter keeps a map from event names to arrays of listeners. on adds a listener, off removes one, once wraps a listener so it removes itself after the first call, and emit calls each listener with the arguments. Edge cases include removing a listener during emit, listeners added during emit, an off call for a once listener, and an unhandled error event.

Full answer

The observer pattern lets one part of a program announce events while others react, without the announcer knowing who is listening. An event emitter is the usual building block, and writing one is a common interview exercise.

The design is a Map from event name to an array of listener functions. on(name, fn) pushes the function and returns this so calls can be chained. off(name, fn) removes the listener. emit(name, ...args) calls every listener in order with this set to the emitter and returns true if there was at least one listener.

once(name, fn) registers a wrapper that first removes itself and then calls the original. The wrapper keeps a reference to the original, so off(name, fn) can still remove a once listener before it fires.

Edge cases that interviewers look for:

  • Removing or adding listeners during emit. Iterating over the live array would skip or repeat listeners, so emit iterates over a copy.
  • A listener that throws. Decide whether the error stops the other listeners (the simple version lets it propagate) and document it.
  • Node's convention that emitting 'error' with no listener throws the error instead of silently ignoring it.
  • The same function added twice, which is called twice and needs two off calls.
  • Memory leaks from listeners that are never removed. Node warns after ten listeners per event for this reason.
  • Order: listeners run in the order they were added, and prependListener adds one at the front.

A return value from on that removes the listener, like const stop = emitter.on(...), is a common convenience.

javascript
class EventEmitter {
  #listeners = new Map();

  on(name, listener) {
    const list = this.#listeners.get(name) ?? [];
    list.push(listener);
    this.#listeners.set(name, list);
    return this;
  }

  off(name, listener) {
    const list = this.#listeners.get(name);
    if (!list) return this;
    const index = list.findIndex((item) => item === listener || item.original === listener);
    if (index !== -1) list.splice(index, 1);
    if (list.length === 0) this.#listeners.delete(name);
    return this;
  }

  once(name, listener) {
    const wrapper = (...args) => {
      this.off(name, wrapper);
      return listener.apply(this, args);
    };
    wrapper.original = listener;
    return this.on(name, wrapper);
  }

  emit(name, ...args) {
    const list = this.#listeners.get(name);
    if (!list || list.length === 0) {
      if (name === 'error') throw args[0] instanceof Error ? args[0] : new Error('Unhandled error event');
      return false;
    }
    for (const listener of [...list]) listener.apply(this, args);
    return true;
  }

  listenerCount(name) {
    return this.#listeners.get(name)?.length ?? 0;
  }
}

const emitter = new EventEmitter();
const log = [];
const greet = (name) => log.push(`hello ${name}`);

emitter.on('greet', greet).on('greet', (name) => log.push(`welcome ${name}`));
emitter.once('greet', (name) => log.push(`first time only for ${name}`));
console.log(emitter.emit('greet', 'Asha'), emitter.emit('greet', 'Ravi'), emitter.emit('nobody'));
console.log(log);

emitter.off('greet', greet);
log.length = 0;
emitter.emit('greet', 'Meera');
console.log(log, emitter.listenerCount('greet'));

const cancelled = () => log.push('should not run');
emitter.once('ping', cancelled);
emitter.off('ping', cancelled);
console.log(emitter.emit('ping'));

const stable = new EventEmitter();
const order = [];
stable.on('x', function first() {
  order.push('first');
  stable.off('x', first); // removing during emit
  stable.on('x', () => order.push('added during emit'));
});
stable.on('x', () => order.push('second'));
stable.emit('x');
stable.emit('x');
console.log(order);

try {
  emitter.emit('error', new Error('boom'));
} catch (error) {
  console.log('unhandled error event:', error.message);
}
emitter.on('self', function () {
  log.push(this === emitter);
});
log.length = 0;
emitter.emit('self');
console.log(log);

Run with Node.js v24.22.1 as js-82.js; two runs gave identical output. Output: true true false [ 'hello Asha', 'welcome Asha', 'first time only for Asha', 'hello Ravi', 'welcome Ravi' ] [ 'welcome Meera' ] 1 false [ 'first', 'second', 'second', 'added during emit' ] unhandled error event: boom [ true ]

Key points

  • Store listeners in a Map from event name to an array of functions.
  • on adds, off removes, emit calls in order and reports whether anyone listened.
  • once wraps the listener so it removes itself first; off must still find the original.
  • Emit over a copy so changes during emit do not skip or repeat listeners.
  • An error event without a listener should throw; leaked listeners are a memory risk.

Common mistakes

  • Looping over the live listener array while listeners add or remove themselves.
  • Making once impossible to remove because the wrapper hides the original function.
  • Returning undefined from on, which prevents chaining.
  • Silently ignoring an error event with no listener.

Follow-ups

  • How would you add prependListener and a maximum listener warning?
  • How would you support async listeners and wait for all of them?
  • How does the browser EventTarget differ from this design?

Tips

  • Write once as a wrapper that removes itself first, then calls the listener.
  • Mention the copy-on-emit edge case before being asked.
  • Return this from on, off, and once to allow chaining.