hand sketched logo of electrons orbiting a nucleus

TIL: When to use `Object.create(null)`

I remember being told you can use Object.create(null) to create an object without a prototype. I didn't immediately know when you would want to do that. I just bumped into a case!

class EventEmitter {
  /* stuff */
}

const eventEmitter = new EventEmitter();
eventEmitter.on('foo', () => console.log('foo'));
eventEmitter.emit('foo'); // logs 'foo'

// possible issue
eventEmitter.on('toString', () => console.log('toString'));
eventEmitter.emit('toString'); // depends on EventEmitter implementation, this might throw

Internally, if the data structure in EventEmitter for storing event listeners is an object then when accessing the value at toString could go up the prototype chain and return a function (when we'd be expecting undefined or an array of listeners).

To avoid this, we can use Object.create(null) to create an object without a prototype.

class EventEmitter {
  private listeners: Record<string, Function[]> = Object.create(null);
  // ...
}

You could also use Map instead of Object.create(null).

class EventEmitter {
  private listeners: Map<string, Function[]> = new Map();
  // ...
}