What is the output of the following? “`js class EventEmitter { #handlers = {}; on(event, handler) { (this.#handlers[event] ??= []).push(handler); } emit(event, data) { this.#handlers[event]?.forEach(h => h(data)); } } const ee = new EventEmitter(); ee.on(‘test’, v => console.log(v * 2)); ee.emit(‘test’, 5); ee.emit(‘missing’, 5); “`
Key points
- The 'test' event triggers the handler to log 5 * 2 = 10
- The 'missing' event has no handler, so nothing is output
- The EventEmitter class allows for event handling in JavaScript
Ready to go further?
