Challenge - 5 Problems
EventEmitter Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this EventEmitter code?
Consider this Node.js code using EventEmitter. What will it print when run?
Node.js
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('greet', () => { console.log('Hello!'); }); emitter.emit('greet'); emitter.emit('greet');
Attempts:
2 left
💡 Hint
Think about how many times the 'greet' event is emitted and how many listeners are attached.
✗ Incorrect
The 'greet' event listener runs each time the event is emitted. Since emit is called twice, 'Hello!' prints twice.
❓ state_output
intermediate2:00remaining
What is the value of count after this EventEmitter code runs?
Look at this code snippet. What is the final value of the variable count?
Node.js
const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('increment', () => { count += 1; }); emitter.emit('increment'); emitter.emit('increment'); emitter.emit('increment');
Attempts:
2 left
💡 Hint
Each 'increment' event increases count by 1.
✗ Incorrect
The listener adds 1 to count each time 'increment' is emitted. It is emitted 3 times, so count is 3.
📝 Syntax
advanced2:00remaining
Which option causes a syntax error in EventEmitter usage?
Which of these code snippets will cause a syntax error when using EventEmitter?
Attempts:
2 left
💡 Hint
Check the syntax for calling methods in JavaScript.
✗ Incorrect
Option A misses parentheses around the arguments, causing a syntax error.
🔧 Debug
advanced2:00remaining
Why does this EventEmitter code not print anything?
This code does not print anything. What is the reason?
Node.js
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.emit('start'); emitter.on('start', () => { console.log('Started'); });
Attempts:
2 left
💡 Hint
Think about the order of adding listeners and emitting events.
✗ Incorrect
Listeners must be added before emitting events to catch them. Here, emit runs before listener is added.
🧠 Conceptual
expert2:00remaining
What happens if an EventEmitter listener throws an error and there is no 'error' listener?
In Node.js EventEmitter, if a listener throws an error and no 'error' event listener is registered, what happens?
Attempts:
2 left
💡 Hint
Consider Node.js default behavior for unhandled errors in EventEmitter.
✗ Incorrect
If no 'error' listener is registered, an error thrown in a listener causes the Node.js process to crash.