Event-Driven Programming — Explained with Examples
Event-driven programming is a paradigm in which the flow of a program is determined by events — user actions (clicks, keypresses), sensor outputs, messages from other programs, or system signals. The program listens for events and dispatches them to registered event handlers or callbacks.
This paradigm is fundamental to graphical user interfaces (GUI), web browsers, Node.js (event loop), and the observer pattern. An event-driven program typically has a main loop (event loop) that waits for events and distributes them. It contrasts with sequential programming where the programmer controls execution order. Event-driven systems are inherently asynchronous and often combined with Reactive Programming and Functional Programming styles.
Real-world analogy. Event-driven programming is like a restaurant with call buttons at each table. The waiter (event loop) waits for a button press (event). When Table 3 presses the button, the waiter responds by going to Table 3 (handler). The waiter doesn’t follow a fixed route — they react to events as they happen.
Example (JavaScript — browser event):
document.getElementById("myButton")
.addEventListener("click", (event) => {
console.log("Button clicked at", event.clientX, event.clientY);
// Response: maybe show a modal, fetch data, etc.
});Example (Node.js — custom event):
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("user:login", (username) => console.log(`${username} logged in`));
emitter.emit("user:login", "alice");Related terms: Reactive Programming, Functional Programming, Observer Pattern, Procedural Programming, OOP
Related tutorial: Event-Driven Architecture
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro