Event Listeners
8 min · JavaScript
Run code when something happens, the same pattern that powers clicks on the web.
Enemy 1 of 5
This code registers a function for a click event, then fires that event so the function runs. Code can wait and react when something happens. Press Run to see it.
Why this works
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.