Question presented to candidate: "Beyond 'on() subscribes, emit() calls listeners' — what does EventEmitter actually store internally, and does it treat one listener the same way as ten?"
What a strong answer should cover:
- Internally, an
EventEmitterinstance keeps its listeners in a single property,_events— a plain object mapping event names to listener(s), created withObject.create(null)(a null-prototype object) specifically to avoid collisions with inherited properties liketoStringorconstructorif an event happened to be named that. - 📌 A real, verifiable optimization: for an event with exactly one listener,
_events[eventName]stores the bare function directly, not wrapped in an array. Only when a second listener is added for the same event does that slot convert into a genuine array — confirmed directly, not merely documented, by inspecting_eventsbefore and after adding a second listener. .emit(event, ...args)looks up_events[event], and if it exists, calls it (or iterates the array and calls each) synchronously, in order — this is the same mechanism underlying the listener-ordering and.once()-removal behavior verified in the dedicated EventEmitter-basics question, now traced to its actual internal storage..once(event, listener)is implemented as a thin wrapper: internally, it registers a listener that, on its first invocation, removes itself (via the emitter's own.removeListener) before calling the original callback — it is not a separate internal mechanism from.on(), just.on()plus automatic self-removal logic layered on top.- The special-cased
'error'event behavior (verified with a real thrown exception in the dedicated EventEmitter-basics question) is implemented as an explicit check inside.emit()itself: if the event name is exactly'error'and_events.errorhas no listener,.emit()throws the error argument directly rather than silently returningfalsethe way it would for any other unlistened event. - A precise answer connects this to performance: the single-listener bare-function optimization avoids allocating an array for the extremely common case of exactly one listener per event, which matters given how pervasively
EventEmitterunderlies Streams, sockets, and HTTP internals throughout Node.
Clarifying questions expected:
- "Is the interviewer asking about the public API (covered in the dedicated basics question) or genuinely the internal storage mechanism?" — this question is specifically about the latter.
- "Does the answer need to address performance characteristics, or just correctness of the mechanism?"
Code / implementation expected: Yes — directly inspecting _events before and after adding a second listener, showing the bare-function-to-array conversion, is the concrete, convincing demonstration of genuine internal understanding.