Skip to content
jshacks.dev
Functions

Implement an EventEmitter From Scratch in JavaScript

Implement an EventEmitter from scratch in JavaScript with on, off, once and emit, handle errors and listener removal during emit, and compare with Node.js.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, TypeScript, Vite and npm logos.

An event emitter lets one part of a program announce that something happened and any number of other parts react to it, without the announcer knowing who is listening. Node.js ships one as node:events, browsers have EventTarget, and the interview version asks you to write the small core yourself: on, off, once and emit. The simple answer is a map from event names to arrays of functions. The details decide the quality: the order listeners run in, what this is, what happens when a listener removes itself during emit, how once can be removed before it fires, and what to do with an error event nobody listens to. This post builds the class on Node.js 24 step by step with output at each stage and compares it with the built-in EventEmitter.

The data structure

Keep a Map from event name to an array of listener functions. A Map accepts any value as a key, including symbols, which Node.js also allows for event names.

JavaScript
class Emitter {
  #listeners = new Map();

  on(event, listener) {
    if (typeof listener !== "function") {
      throw new TypeError("listener must be a function");
    }

    const list = this.#listeners.get(event) ?? [];

    list.push(listener);
    this.#listeners.set(event, list);

    return this;
  }

  emit(event, ...args) {
    const list = this.#listeners.get(event);

    if (!list || list.length === 0) {
      return false;
    }

    for (const listener of list) {
      listener.apply(this, args);
    }

    return true;
  }
}

const emitter = new Emitter();

emitter.on("greet", (name) => console.log(`hello, ${name}`));
emitter.on("greet", (name) => console.log(`welcome, ${name}`));

console.log(emitter.emit("greet", "Ana"));
console.log(emitter.emit("unknown"));
Text
hello, Ana
welcome, Ana
true
false

Listeners run synchronously, in the order they were added, before emit returns. emit returns true when at least one listener ran and false when there were none, which is what Node.js does, and it lets a caller detect an event nobody handled. on returns this so calls can be chained. The private field #listeners keeps the map out of reach, which prevents code outside the class from changing the lists.

listener.apply(this, args) sets this inside a regular function listener to the emitter, as Node.js does. Arrow functions ignore it.

Removing listeners with off

To remove a listener you need the same function reference that was added. off finds it and removes one occurrence. Here is the whole class in one place, with off, once, the rules for removal during emit and the error event, which the sections below explain.

JavaScript
class EventEmitterLite {
  #events = new Map();

  on(event, listener) {
    if (typeof listener !== "function") {
      throw new TypeError("listener must be a function");
    }

    const list = this.#events.get(event) ?? [];

    list.push(listener);
    this.#events.set(event, list);

    return this;
  }

  off(event, listener) {
    const list = this.#events.get(event);

    if (!list) {
      return this;
    }

    const index = list.findLastIndex((entry) => entry === listener || entry.original === listener);

    if (index !== -1) {
      list.splice(index, 1);
    }

    if (list.length === 0) {
      this.#events.delete(event);
    }

    return this;
  }

  once(event, listener) {
    const wrapper = (...args) => {
      this.off(event, wrapper);
      listener.apply(this, args);
    };

    wrapper.original = listener;

    return this.on(event, wrapper);
  }

  emit(event, ...args) {
    const list = this.#events.get(event);

    if (!list || list.length === 0) {
      if (event === "error") {
        throw args[0] instanceof Error ? args[0] : new Error(`Unhandled error: ${String(args[0])}`);
      }

      return false;
    }

    for (const listener of [...list]) {
      listener.apply(this, args);
    }

    return true;
  }

  listenerCount(event) {
    return this.#events.get(event)?.length ?? 0;
  }
}

const bus = new EventEmitterLite();
const onData = (value) => console.log("data:", value);

bus.on("data", onData);
bus.emit("data", 1);
bus.off("data", onData);

console.log(bus.emit("data", 2), bus.listenerCount("data"));
Text
data: 1
false 0

After off, no listener remains, so the second emit returns false, and the count is zero. findLastIndex was added in ES2023 and works in Node.js 18 and later. It removes the most recently added copy of the function, which matches Node.js: if the same function was added twice, off removes one entry per call.

once

once must run the listener at most one time. The wrapper removes itself and then calls the original. It also keeps a reference to the original in wrapper.original, so off(event, original) can find and remove a once listener before it fires. That was the reason for the entry.original === listener check in off.

JavaScript
const single = new EventEmitterLite();
const hello = () => console.log("hello once");

single.once("hi", hello);
single.off("hi", hello);
single.emit("hi");

single.once("hi", hello);
single.emit("hi");
single.emit("hi");

console.log(single.listenerCount("hi"));
Text
hello once
0

The first once is removed through the original function before anything fires, so the first emit prints nothing. The second is registered again, fires on the next emit and removes itself, so the third emit is silent and the count is zero. The order inside the wrapper matters: removing before calling guards against a listener that triggers the same event again, which would otherwise call it twice.

Changing listeners during emit

What happens if a listener removes itself or another listener while emit is looping? If the loop runs over the live array, splice shifts the elements, and the next listener is skipped.

JavaScript
const unsafe = new Map([["tick", []]]);
const calls = [];

const a = () => {
  calls.push("a");
  unsafe.get("tick").splice(0, 1);
};

const b = () => calls.push("b");
const c = () => calls.push("c");

unsafe.get("tick").push(a, b, c);

for (const listener of unsafe.get("tick")) {
  listener();
}

console.log(calls.join(","));
Text
a,c

After a removes itself, b moves to index 0, and the loop's next index is 1, which is c. The listener b is skipped and never runs. The fix, used in emit above, is to iterate over a copy, [...list]. Then every listener that was registered at the moment of emit runs once, and changes made during the call apply to the next emit. Node.js does the same, and documents it.

JavaScript
const safe = new EventEmitterLite();
const order = [];

const first = () => {
  order.push("first");
  safe.off("tick", first);
};

safe.on("tick", first).on("tick", () => order.push("second"));
safe.on("tick", () => order.push("third"));

safe.emit("tick");
safe.emit("tick");

console.log(order.join(","));
Text
first,second,third,second,third

The first emit runs all three, including the one that removes itself. The second emit runs only the two that remain. A listener added during an emit is not called in that same emit, because the copy was made before it was added.

The error event

Node.js gives error a special meaning: if an error event is emitted and nobody listens, emit throws the error. That prevents failures from vanishing silently. The implementation above does the same.

JavaScript
const failing = new EventEmitterLite();

try {
  failing.emit("error", new Error("disk full"));
} catch (error) {
  console.log("thrown:", error.message);
}

failing.on("error", (error) => console.log("handled:", error.message));
failing.emit("error", new Error("disk full"));
Text
thrown: disk full
handled: disk full

With no listener, the error is thrown from emit. With a listener, it is delivered and nothing is thrown. Because listeners run synchronously, an exception thrown by a listener propagates out of emit and stops the remaining listeners from running. Node.js behaves the same, and a robust emitter either documents this or wraps each call in try and catch.

Prepend, listener limits and async emit

Real emitters add a few more features. prependListener adds to the front of the list so a listener runs first. A listener limit warns when more than ten listeners are added for one event, which usually signals a leak, for example a component that adds a listener on every render and never removes it. And some code needs emit to wait for async listeners, which the base class does not do, because it ignores the return values of the listeners.

For an async emit, the design choice is between running listeners one after another, which keeps their order and stops at the first failure, and running them together with Promise.all, which is faster and rejects on the first failure while the others keep running. Pick one and document it. Keep the synchronous emit as it is, since callers rely on its timing.

Comparing with Node.js

JavaScript
import { EventEmitter } from "node:events";

const real = new EventEmitter();

real.on("data", (value) => console.log("real:", value));
real.once("data", () => console.log("only once"));

console.log(real.emit("data", 1), real.emit("data", 2));
console.log(real.listenerCount("data"));
Text
real: 1
only once
real: 2
true true
1

The built-in version has the same semantics for on, once, emit and the error event, and adds prependListener, removeAllListeners, setMaxListeners, eventNames, rawListeners and the newListener event. In real code use it, or EventTarget, which is the web standard and also available in Node.js.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("listeners run in order and receive arguments", () => {
  const e = new EventEmitterLite();
  const seen = [];

  e.on("x", (a, b) => seen.push(["first", a, b]));
  e.on("x", (a) => seen.push(["second", a]));
  e.emit("x", 1, 2);

  assert.deepEqual(seen, [["first", 1, 2], ["second", 1]]);
});

test("once fires a single time", () => {
  const e = new EventEmitterLite();
  let count = 0;

  e.once("x", () => (count += 1));
  e.emit("x");
  e.emit("x");

  assert.equal(count, 1);
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

How to present it

Draw the structure first: a map of arrays. Write on and emit, run the example, and then ask yourself what breaks. The strongest answers raise the iteration problem on their own, saying that a listener can remove itself during emit, and show the copy of the array as the fix. After that, once with its wrapper and the original property, and the special error event.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.