Skip to the solution
MediumFrontend6 min read

Implement EventEmitter (on/off/once/emit) — Node style

1.1k views

The problem

Problem, as an interviewer would state it: "Implement a Node-style EventEmitter class with on(event, fn), off(event, fn), once(event, fn), and emit(event, ...args)."

Examples:

Code
const emitter = new EventEmitter();
emitter.on("data", (x) => console.log("got", x));
emitter.emit("data", 42); // "got 42"

Clarifying questions expected:

  • If a listener calls off() on itself (or another listener) WHILE emit is iterating, should that be handled safely?
  • Does once() need to also support being manually removed via off() before it ever fires?
  • Should emit() return a boolean indicating whether any listeners existed, matching Node's own real convention?

Code / implementation expected: Yes — real, direct proof of all 4 core methods, including the subtlest case: a self-removing listener executing mid-emit.

  • event-emitter
  • pubsub

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: EventEmitter correctly handles on/off/once, and a listener removing itself mid-emit does not break other listeners

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 82 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement a Memoized Selector That Only Recomputes When Its Specific Inputs Change (Reselect-Style)

Continue