Events and callbacks help your program respond to actions or changes. Choosing between them makes your code easier to understand and work with.
Events vs callbacks decision in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
/* Callback example */ function doTask(callback) { // do something callback(null, 'done'); } doTask((err, result) => { if (err) { console.error(err); } else { console.log(result); } }); /* Event example */ const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('done', (result) => { console.log(result); }); emitter.emit('done', 'done');
Callbacks are functions passed to run after a task finishes.
Events let many listeners react to named signals from an object.
Examples
Node.js
const fs = require('fs'); fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data.toString()); });
Node.js
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('message', (msg) => { console.log('Received:', msg); }); emitter.emit('message', 'Hello!');
Sample Program
This program shows both ways: an event emitter and a callback. Both wait 1 second and then print a message.
Node.js
const EventEmitter = require('events'); class Task extends EventEmitter { run() { setTimeout(() => { this.emit('done', 'Task completed'); }, 1000); } } // Using events const task = new Task(); task.on('done', (msg) => { console.log('Event says:', msg); }); task.run(); // Using callback function runTask(callback) { setTimeout(() => { callback('Callback says: Task completed'); }, 1000); } runTask((message) => { console.log(message); });
Important Notes
Use callbacks for simple, single responses.
Use events when many parts need to react or for more flexible design.
Events can help avoid deeply nested callbacks, making code cleaner.
Summary
Callbacks run one function after a task finishes.
Events let many listeners respond to named signals.
Choose callbacks for simple tasks, events for complex or multiple reactions.
Practice
1. Which statement best describes when to use callbacks versus events in Node.js?
easy
Solution
Step 1: Understand callbacks and events roles
Callbacks run one function after a task finishes, suitable for simple, single responses.Step 2: Understand events usage
Events allow many listeners to respond to named signals, useful for complex or multiple reactions.Final Answer:
Use callbacks for simple single responses and events for multiple listeners. -> Option AQuick Check:
Callbacks = single response, Events = multiple listeners [OK]
Hint: Callbacks = one response; events = many listeners [OK]
Common Mistakes:
- Thinking events are only for synchronous code
- Believing callbacks handle all errors exclusively
- Assuming events completely replace callbacks
2. Which of the following is the correct syntax to add an event listener in Node.js?
easy
Solution
Step 1: Recall Node.js event listener syntax
The standard method to add an event listener is using emitter.on with event name and callback.Step 2: Check each option for syntax correctness
emitter.on('eventName', callbackFunction); uses correct syntax with parentheses and comma. emitter.addListener('eventName' callbackFunction); misses a comma. Options A and D use invalid method names.Final Answer:
emitter.on('eventName', callbackFunction); -> Option DQuick Check:
Correct event listener syntax = emitter.on(...) [OK]
Hint: Use emitter.on('event', callback) for events [OK]
Common Mistakes:
- Missing comma between arguments
- Using incorrect method names like listen or callback
- Confusing addListener syntax without comma
3. What will be the output of this Node.js code snippet?
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', () => console.log('Hello!'));
emitter.emit('greet');
emitter.emit('greet');medium
Solution
Step 1: Understand event listener and emit behavior
Each call to emitter.emit triggers all listeners for that event. Here, 'greet' event has one listener printing 'Hello!'.Step 2: Count how many times emit is called
emit('greet') is called twice, so the listener runs twice, printing 'Hello!' two times.Final Answer:
Hello! printed twice -> Option CQuick Check:
emit triggers listeners each time = output twice [OK]
Hint: emit calls listeners every time it's invoked [OK]
Common Mistakes:
- Thinking emit triggers listener only once
- Expecting no output without callback arguments
- Confusing event registration with callback invocation
4. Identify the error in this Node.js code using callbacks and events:
const EventEmitter = require('events');
const emitter = new EventEmitter();
function task(callback) {
emitter.emit('done');
callback();
}
task(() => console.log('Callback finished'));
emitter.on('done', () => console.log('Event done'));medium
Solution
Step 1: Check order of event listener and task call
The event listener is added after task() is called, so the 'done' event may emit before listener exists.Step 2: Understand event emission timing
task emits 'done' synchronously when called, but listener is added after task() call, so emit happens before listener setup.Final Answer:
The event listener is added after task is called, so event may be missed. -> Option AQuick Check:
Listener must be added before event emit [OK]
Hint: Add event listeners before emitting events [OK]
Common Mistakes:
- Adding listeners after emitting events
- Confusing callback order with event order
- Assuming setTimeout needs no delay argument
5. You want to notify multiple parts of your Node.js app when a file download finishes, but also run a cleanup callback once. Which approach fits best?
hard
Solution
Step 1: Analyze notification needs
Multiple parts need to be notified, which fits event emitters allowing many listeners.Step 2: Analyze cleanup requirement
Cleanup runs once after download, suitable for a single callback after task completion.Step 3: Combine approaches
Use events for multiple notifications and a callback for single cleanup to keep code clear and efficient.Final Answer:
Use an event emitter to notify multiple listeners and a callback for cleanup after download. -> Option BQuick Check:
Events = multiple notifications, callback = single cleanup [OK]
Hint: Events for many, callback for one-time cleanup [OK]
Common Mistakes:
- Trying to use only callbacks for multiple notifications
- Using multiple callbacks instead of events
- Using events for single cleanup unnecessarily
