Frontend101 logoFrontend101

Building an EventEmitter in JavaScript

Satish Shriwas·Oct 29, 2026·2 min read
Original on Medium ↗

Ever wondered how JavaScript lets you subscribe to events and react when something happens? Let’s build a simple EventEmitter from scratch — a common frontend machine-coding interview problem.

Photo by Jakub Żerdzicki on Unsplash

🧠 The Idea

An EventEmitter follows a simple pattern:

  • on() — Subscribe to an event.
  • off() — Unsubscribe a listener.
  • emit() — Trigger an event and notify its listeners.

For example:

const emitter = new EventEmitter();
emitter.on('foo', (value) => {
console.log(value);
});
emitter.emit('foo', 42); // 42

💻 Implementation

We’ll use a JavaScript Map to store event names and their listeners.

export default class EventEmitter {
constructor() {
this.event = new Map();
}
on(eventName, listener) {
if (!this.event.has(eventName)) {
this.event.set(eventName, []);
}
this.event.get(eventName).push(listener);
return this;
}
off(eventName, listener) {
const listeners = this.event.get(eventName);
if (!listeners) return this;
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
if (listeners.length === 0) {
this.event.delete(eventName);
}
return this;
}
emit(eventName, ...args) {
const listeners = this.event.get(eventName);
if (!listeners || listeners.length === 0) {
return false;
}
listeners.forEach((listener) => {
listener.call(this, ...args);
});
return true;
}
}

🔍 How It Works

1. on() — Register a listener

If the event doesn’t exist, create an empty array. Then add the listener.

emitter.on('foo', callback);

2. off() — Remove a listener

Find the first matching listener and remove it. If no listeners remain, delete the event from the Map.

3. emit() — Trigger the event

Retrieve all listeners, pass the supplied arguments to each one, and return true. If no listeners exist, return false.

emitter.emit('foo', 10);

The ...args syntax allows an event to receive any number of arguments.

⚡ Complexity Analysis

Let n be the number of listeners registered for an event.

  • on(): O(1) amortized
  • off(): O(n) — finding a listener takes linear time.
  • emit(): O(n) — each listener is invoked once.

🎯 Interview Takeaways

  • Use a Map to safely store arbitrary event names.
  • Preserve listener registration order.
  • Remove only one matching registration when duplicates are allowed.
  • Return this from on() and off() to support method chaining.
  • Make sure emit() handles unknown events gracefully.

The key insight: An EventEmitter is essentially a mapping between event names and arrays of callback functions.

A small implementation, but a great exercise for understanding callbacks, data structures, and JavaScript’s event-driven programming model.