Event Listeners
8 min · JavaScript
Run code when something happens — the same pattern that powers clicks on the web.
Enemy 1 of 5
Everything you've written so far runs top to bottom the moment the program starts. But a huge amount of real JavaScript — especially in the browser — is reactive: code that sits and waits, then runs only when something happens, like a user clicking a button or a page finishing loading. That pattern is called event-driven programming.
On a web page, addEventListener('click', handler) tells the browser: run this handler function whenever the user clicks this particular element. You're not calling handler yourself — you're registering it in advance, and the browser calls it for you at the right moment, possibly much later, possibly never if the click never happens.
This runner doesn't have a web page to click on, but Node's EventEmitter captures the exact same pattern in plain code: .on("click", handler) registers a function to run for a named event, and .emit("click") is what actually fires that event, triggering every handler registered for it. This lets you practice the register-then-react pattern without a browser.
Loading editor...