Skip to main content

What does the emit() method do?

1. What emit() does

The .emit(eventName, [...args]) method fires an event named eventName and calls all handlers (listeners) that were subscribed to it via .on() or .once().

Example:

javascript
const EventEmitter = require('events'); const emitter = new EventEmitter(); // Subscribe emitter.on('greet', (name) => { console.log(`Hello, ${name}!`); }); // Fire the event emitter.emit('greet', 'Tim');

Output:

javascript
Hello, Tim!

What happened:

  1. .emit('greet', 'Tim') creates the greet event;
  2. Node.js finds all listeners for greet;
  3. it calls each of them, passing 'Tim' as an argument;
  4. if there are no listeners, nothing happens.

2. Syntax

javascript
emitter.emit(eventName[, ...args])
  • eventName, a string (the event's name);
  • ...args, any values that will be passed to the listeners.

3. How it works under the hood

When .emit() is called:

  1. Node.js looks up its internal map of listeners (_events);
  2. checks whether there are listeners for eventName;
  3. if there are, it calls them in registration order (.on() -> .once());
  4. if it's a .once() listener, it's removed after the call;
  5. if the 'error' event is emitted with no listener, an exception is thrown and the process terminates.

Special behavior for 'error'

If you call:

javascript
emitter.emit('error', new Error('Something went wrong'));

and there's no 'error' listener, Node.js will:

  • throw an error (Uncaught Error);
  • terminate the process.

That's why it's good practice to always add an 'error' handler:

javascript
emitter.on('error', (err) => { console.error('Error caught:', err.message); });

4. Return value

.emit() returns:

  • true, if the event has at least one listener;
  • false, if it has none.
javascript
console.log(emitter.emit('greet')); // true console.log(emitter.emit('unknown')); // false

5. Example with several listeners

javascript
emitter.on('update', () => console.log('Update received')); emitter.on('update', () => console.log('Data processed')); emitter.emit('update');

Output:

javascript
Update received Data processed

6. Example with arguments

javascript
emitter.on('sum', (a, b) => { console.log('Sum =', a + b); }); emitter.emit('sum', 3, 7);

Output:

javascript
Sum = 10

Summary

The .emit() method:

  • fires an event on an EventEmitter object;
  • calls all handlers subscribed via .on() and .once();
  • can pass arguments to the listeners;
  • returns true if there are listeners, and false if there aren't.

This is the main way to "tell" the system that something happened, so other parts of the code can react.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.