Skip to content
JavaScript·Intermediate·Coding·1 min read

Why is an unsubscribe mechanism critical to an observer implementation?

Short interview answer

Without a way to remove a listener, every subscription lives for the lifetime of the emitter itself, which is exactly the retained-closure memory-leak pattern that forgotten event listeners and timers also create.

Example

JavaScript
function createEmitter() {  const listeners = new Set();  return {    on(fn) {      listeners.add(fn);      return () => listeners.delete(fn); // return an unsubscribe    },    emit(data) { listeners.forEach((fn) => fn(data)); },  };}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to JavaScript design patterns

Related questions