The Programming Shortcut: JavaScript
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about event-driven programming.
You already own a programming environment
Look up from this article for a second. The program you are reading it in is a browser, and every browser ships with a JavaScript engine, a console for talking to it, and a full set of tools for poking at what it’s doing. You didn’t install any of that. Nobody asked you to. It came with the thing you use to read the news.
So JavaScript is already on nearly every computer and phone you’ve ever touched, and it got there by being made for one job: making a web page do something when you touch it. Not crunching numbers. Not reading files. Responding.
That job forces JavaScript to be very good at an idea most programs only meet later, and usually the hard way: code that waits for things to happen. A click. A key. A timer running out. An answer arriving from a server somewhere. That idea is called event-driven programming, and it’s what this article is about. JavaScript is simply the place where you can’t avoid it.
What carries over
You already know variables, decisions, loops, functions and records. JavaScript has all of them, spelled much as you’d guess. Here’s how a few of them line up:
| What you know | lux | JavaScript |
|---|---|---|
| a variable | let (fixed), var (changes) | const (fixed), let (changes) |
| a function | func add(a: int, b: int) -> int | function add(a, b) |
| a record | struct | an object: { dish: "Toast", seconds: 2 } |
| a value that might be missing | Option | null, and also undefined |
| an error you expect | Result | an exception, or a rejected promise (below) |
| when types are checked | before running, every branch | never (why that matters) |
| waiting for a person | input() stops the program | a listener; nothing stops |
That last row is the article. Everything above it you can pick up as you go.
Edit, save, refresh
Your one tool is the browser you already have, plus any text editor. Make a folder,
and in it a file called waiting.html:
<!doctype html>
<title>Waiting</title>
<button>Click me</button>
<script>
console.log("1. The script starts");
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("3. Somebody clicked");
});
console.log("2. The script is finished");
</script>
Open the file in your browser. You’ll see a lonely button. To see what the script said, open the browser’s developer tools with F12 (or Cmd+Option+I on a Mac) and pick the Console tab. If your browser does something different, MDN Web Docs, Mozilla’s reference for the web, has the details for each one.
The console says:
1. The script starts
2. The script is finished
Now click the button. A third line appears. Click again, and another.
That’s how you’ll work from here: edit the file, save it, refresh the page, watch the console. Keep the console open from here on. It’s where JavaScript talks back.
A few pieces of that file are new, and each one gets a sentence.
document.querySelector("button") finds the first button on the page.
console.log prints to the console. And () => { ... } is an arrow function: a
function with no name, written right at the spot where it’s needed. It’s an
ordinary function in every other way.
But look at what just happened, because it’s strange. The script ran from top to bottom and finished. It said so: “The script is finished.” And yet the third line printed afterward, as many times as you liked. Something ran your code after your program was over.
Code that waits
Your program ends, and the page keeps going
In most of the programs you’ve written, the program is in charge. It starts at the
top, does its work, maybe stops to ask for input, and ends. If you know lux,
input() is a good picture of this: the whole program halts on that line until
somebody types, and nothing else happens in the meantime.
A web page can’t work like that. It has to scroll, play a video, respond to a dozen buttons and keep a clock ticking, all at once, while the person in front of it does whatever they please. If the page stopped to wait for one thing, every other thing would freeze.
So JavaScript in a browser turns the arrangement around. Your script doesn’t wait for anything. It runs once, at the start, and its job is to set things up: to tell the browser “when this happens, call that.” Then it ends. From then on the browser is in charge, and your code runs only when the browser calls it.
That’s event-driven programming. Three words carry it:
An event is something that happened: a click, a key press, the page finishing loading, a timer running out, data arriving.
A listener (also called a handler) is a function you want called when a particular event happens.
The event loop is the part of the browser that waits for events and calls the matching listeners, one at a time, for as long as the page is open.
Your waiting.html did all three. The script set up one listener and ended. The
event loop kept waiting. Each click was an event, and each time, the loop called
your arrow function.
Handing over a function
The line that made it work is this one:
button.addEventListener("click", () => {
console.log("3. Somebody clicked");
});
addEventListener takes two things: the name of an event, and a function. Not the
result of calling a function, the function itself, handed over like any other
value, for the browser to keep and call later. A function you hand over this way is
called a callback, because someone else will call it back.
If your first language didn’t let you pass functions around as values, this is the one new move in the article. Everything else is built on it. It also explains a classic mistake:
function cheer() {
console.log("Hooray!");
}
button.addEventListener("click", cheer);
button.addEventListener("click", cheer());
The first line hands over cheer, so the browser calls it on each click. The
second line calls cheer right away, while setting up, prints “Hooray!” once,
and hands the browser the result. cheer returns nothing, so that line quietly
sets up no listener at all, and no error tells you so. The parentheses are the difference between “here’s what to do” and “do it now.”
One thing at a time
Here’s where the event loop gets interesting. JavaScript in a page runs on a single thread, meaning one line of your code is running at any moment, never two. The event loop keeps a queue of things that have happened, and it takes them in order. Each listener runs from start to finish before the next one begins. Nothing interrupts it halfway through. This rule has a name, run to completion, and it’s the reason you don’t have to worry about two clicks scrambling the same variable.
You can see the queue with a timer. setTimeout(callback, ms) asks the browser to
call your function after that many milliseconds. What happens if you ask for zero?
<!doctype html>
<title>Zero</title>
<script>
console.log("A: before");
setTimeout(() => console.log("C: the timer"), 0);
console.log("B: after");
</script>
It prints A, B, C. A delay of zero doesn’t mean “now.” It means “as soon as you’re free,” and the browser isn’t free until the current script has run to completion. The timer’s callback waits in the queue like everybody else.
The same rule has a dark side. If one listener takes a long time, everything else waits for it. Try this page:
<!doctype html>
<title>Hog</title>
<button id="hog">Hog the page</button>
<button id="ping">Ping</button>
<script>
document.querySelector("#ping").addEventListener("click", () => {
console.log("ping");
});
document.querySelector("#hog").addEventListener("click", () => {
console.log("hogging for three seconds");
const start = Date.now();
while (Date.now() - start < 3000) {}
console.log("done hogging");
});
</script>
(Date.now() is the current time in milliseconds, so that while loop spins for
three seconds.) Click Hog, then click Ping a few times while it’s busy. Nothing happens. Then the three seconds end, “done hogging”
appears, and all your pings arrive at once. They weren’t lost. They were waiting in
the queue for a loop that was stuck inside your while.
That’s the bargain of event-driven code: every listener should do its bit quickly and hand control back. Which raises an awkward question. What about things that are supposed to take a long time?
Waiting without stopping
Say a listener needs an answer from a server. The answer might take two seconds. You can’t sit in a loop for two seconds, as you just saw. So instead you ask for the answer and say what to do once it arrives: another callback.
That works, and for years it was how everyone did it. But a callback inside a callback inside a callback gets hard to read fast, and errors have nowhere obvious to go. So JavaScript grew a better shape for “later.”
A promise is an object that stands for a value that isn’t here yet. It starts out pending. Later it settles one of two ways: it’s fulfilled with a value, or it’s rejected with an error. Anything slow in a browser hands you a promise right away and settles it when the work is done.
Here’s a tiny promise of your own. wait gives back a promise that is fulfilled
after ms milliseconds:
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
new Promise calls your arrow function with a function, here named resolve, and
you call it when the value is ready. Here the timer calls it for you.
A promise on its own is just a ticket. The good part is how you wait for one.
async and await
Two keywords turn waiting into ordinary-looking code. Mark a function async, and
inside it you may write await in front of a promise. Here’s breakfast:
<!doctype html>
<title>Breakfast</title>
<script>
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function breakfast() {
console.log("toast in");
await wait(1000);
console.log("toast up, butter on");
await wait(500);
console.log("eat");
}
breakfast();
console.log("breakfast() has already returned");
</script>
The console shows:
toast in
breakfast() has already returned
toast up, butter on
eat
Read that order slowly.
breakfast() starts running like any function. It prints “toast in.” Then it hits
await wait(1000). At that moment the function pauses: it sets itself aside,
remembering where it was and every local variable it had, and hands control back to
whoever called it. That’s why “has already returned” prints second. The script
finishes. The event loop is free. Clicks, scrolling and other timers all carry on
as normal.
A second later the promise is fulfilled, and the event loop picks breakfast back
up at the line after the await, as if it had never left. Same function, same
variables, one second later.
So await means “pause this function until the promise settles, and let
everything else carry on.” It doesn’t stop the page, the way the while loop did,
or the program, the way lux’s input() does. It stops one function, politely.
Three more facts make async and await complete.
An async function always returns a promise. Even if it says return 42, the
caller gets a promise that will be fulfilled with 42. That’s how the caller can
await it in turn. Forget the await, and you get the promise itself, not the
value:
<!doctype html>
<title>Forgot</title>
<script>
async function lookUp() {
return 42;
}
async function main() {
const forgot = lookUp();
const remembered = await lookUp();
console.log("The answer is " + forgot);
console.log("The answer is " + remembered);
}
main();
</script>
The first line prints The answer is [object Promise]. If you ever see
[object Promise] on a page you built, somebody forgot an await, and it was
probably you.
A rejected promise becomes an exception at the await. If the thing you’re
waiting for fails (here, a cook function that returns a promise, like the one the
project builds later), the await line throws an error, and an ordinary
try/catch catches it:
try {
const dish = await cook("Soufflé", 3);
console.log(dish);
} catch (error) {
console.log("No soufflé: " + error.message);
}
So errors from slow work land where errors from fast work do, which is the main reason promises replaced nested callbacks. (JavaScript reports failures with exceptions rather than return values. The Java article is the place to go deeper on exceptions.)
Two awaits in a row take turns. To wait for several things at once, start them
all, then wait. Promise.all takes a list of promises and gives you one promise
that’s fulfilled when they all are:
<!doctype html>
<title>Together</title>
<script>
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function main() {
let start = Date.now();
await wait(150);
await wait(100);
console.log("one after the other: about " + (Date.now() - start) + " ms");
start = Date.now();
await Promise.all([wait(150), wait(100)]);
console.log("both at once: about " + (Date.now() - start) + " ms");
}
main();
</script>
The first takes about 250 milliseconds, the second about 150. Nothing ran in parallel here, in the sense of two lines of your code at the same instant. Both timers counted down together while your code was paused.
The browser’s own slow operations all speak promises. The one you’ll use most is
fetch, which asks a server for something:
const response = await fetch("https://example.com/menu.json");
const menu = await response.json();
Two awaits: one for the server to start answering, one for the whole answer to arrive and be read. Talking to a real server brings in a second idea, the server’s side of the conversation, which belongs to the PHP article. This article lets a timer play the server.
The same idea, everywhere
Once you see it, you’ll find it in most languages you meet. Dart, C#, Python,
Rust, Kotlin and Swift all have something called async and await, or very close
to it, and it means the same thing: pause this function until a slow thing finishes,
and let the rest of the program carry on. The engine underneath differs. The shape
in your code doesn’t.
Event-driven programs are everywhere too. A phone app spends its life waiting for taps. A game loop waits for input and frames. A server waits for requests. The browser is just the place where you can watch one run with its lid off.
Where JavaScript lets go
Plain JavaScript checks nothing before it runs (the series introduction shows what that means), so a misspelled name in a listener stays hidden until somebody clicks the button. Event-driven code gives up a subtler guarantee as well.
Inside a single listener, nothing can interrupt you. Across an await, anything
can. While your function is paused, the event loop runs other listeners, and they
can change the very things your function was relying on. When it wakes up, the
world it remembers may be out of date.
Here is the classic version. A search box looks up each word as you type it:
box.addEventListener("input", async () => {
const word = box.value;
const meaning = await lookUp(word);
result.textContent = meaning;
});
Type “cat”. Each letter starts a lookup, so “c”, “ca” and “cat” are all in flight at once. If the answer for “ca” happens to come back last, it overwrites the answer for “cat”, and the page shows a definition for a word you’re no longer looking at. No error. No warning. Just wrong.
The fix is to check, after every await, whether the world still looks the way it
did before:
const meaning = await lookUp(word);
if (box.value !== word) {
return;
}
result.textContent = meaning;
The habit to build: treat every await as a door that someone else may have walked
through.
Beware of reaching for a framework, or for npm (the Node Package Manager, which installs other people’s JavaScript), before you need one. Most JavaScript tutorials start with React, a build tool and a few hundred downloaded packages, and you can spend a week learning those before you’ve written a single listener. Every one of those frameworks is a layer of tidy machinery on top of what you just learned: listeners, an event loop, and promises. Learn the bottom layer first, with nothing but a file and a browser. The frameworks will make much more sense, and you’ll be able to tell when you don’t need one at all, which is more often than their tutorials suggest.
A small project: the Event Kitchen
The project is a kitchen that takes orders. Each dish takes a different time to cook. You can order as much as you like while things are cooking, and dishes come out when they’re done, not when you ordered them. One dish, the soufflé, always fails, so you can see where an error goes.
The project’s two files are in
projects/javascript. Put them in a folder together, or
type them in yourself. First the page, index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The Event Kitchen</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 30rem; margin: 2rem auto; padding: 0 1rem; }
button { font-size: 1rem; margin: 0 0.25rem 0.5rem 0; }
li { margin: 0.25rem 0; }
</style>
</head>
<body>
<h1>The Event Kitchen</h1>
<p>
<button id="tea">Tea</button>
<button id="toast">Toast</button>
<button id="soup">Soup</button>
<button id="souffle">Soufflé</button>
</p>
<p id="pass">The kitchen is quiet.</p>
<ol id="tickets"></ol>
<script src="kitchen.js"></script>
</body>
</html>
Then the program, kitchen.js:
const tickets = document.querySelector("#tickets");
const pass = document.querySelector("#pass");
let cooking = 0;
function cook(dish, seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (dish === "Soufflé") {
reject(new Error("it collapsed"));
} else {
resolve(dish + ": ready");
}
}, seconds * 1000);
});
}
function showPass() {
pass.textContent = cooking === 0 ? "The kitchen is quiet." : cooking + " cooking";
}
async function order(dish, seconds) {
console.log("order in: " + dish);
const ticket = document.createElement("li");
ticket.textContent = dish + ": cooking…";
tickets.append(ticket);
cooking += 1;
showPass();
try {
ticket.textContent = await cook(dish, seconds);
} catch (error) {
ticket.textContent = dish + ": " + error.message;
}
console.log(ticket.textContent);
cooking -= 1;
showPass();
}
document.querySelector("#tea").addEventListener("click", () => order("Tea", 1));
document.querySelector("#toast").addEventListener("click", () => order("Toast", 2));
document.querySelector("#soup").addEventListener("click", () => order("Soup", 4));
document.querySelector("#souffle").addEventListener("click", () => order("Soufflé", 3));
console.log("The kitchen is open. The script has finished; the page is waiting.");
(The real file ends with a block of “Try this next…” ideas, which aren’t printed here.)
Open index.html in your browser with the console showing. Click Soup, Tea, Toast
and Soufflé, quickly, in that order. The console tells the story:
The kitchen is open. The script has finished; the page is waiting.
order in: Soup
order in: Tea
order in: Toast
order in: Soufflé
Tea: ready
Toast: ready
Soufflé: it collapsed
Soup: ready
Four orders went in, and four came out in a different order, each when its own timer finished. Here’s what to notice in the code.
cook is the slow thing. It returns a promise and settles it later, fulfilled for
most dishes and rejected for the soufflé. Its arrow function gets reject as well
as resolve, and calling reject is how a promise says it failed. In a real app this would be fetch
talking to a server; the shape of the code around it would be identical.
order is an async function, so each click starts its own copy, and each copy
pauses at its own await with its own dish and its own ticket. Four orders
means four paused functions, each one waiting for its promise, none of them in the
way of the others. That’s why the page never freezes, and why you can keep clicking.
The page changes through three calls: document.createElement("li") makes a new
list item, tickets.append puts it on the page, and setting textContent changes
the words it shows.
The soufflé’s rejection turns into an exception at the await, and the catch
writes it on the ticket. The kitchen carries on.
And cooking is the shared state that changes while functions are paused. Each
order adds one before its await and takes one away after. Watch the “cooking”
line on the page climb as you click and fall as dishes come out. Every change
happens inside one listener or one resumed function, running to completion, so the
count never gets scrambled.
The script itself finished in a few milliseconds, before you clicked anything, and said so in its last line. Everything after that was the event loop calling you.
What’s left out, and where to go next
This article left out almost all of JavaScript, on purpose. There’s nothing here
about classes, modules, the many ways to build and change a page’s elements, CSS,
or how this behaves (a topic with a reputation). There’s nothing about Node.js,
which runs JavaScript outside the browser with the same event loop underneath.
And there’s nothing about the finer workings of the queue, such as why a fulfilled
promise’s callback jumps ahead of a timer that was due first. MDN’s page on the
JavaScript execution model
covers that when you’re curious.
For JavaScript itself, the best place to keep going is MDN’s JavaScript guide, written by the people who document the browsers. When you want to go deeper on the subject of this article, read its pages on using promises and on events. And when you’re ready to have JavaScript’s types checked before it runs, the TypeScript article picks up there.
A message waiting for you
This page is a web page too, and it has been running a little JavaScript the whole time you’ve been reading. It left you a message.
Open the console right here, on this article, with F12 (or Cmd+Option+I on a Mac). Read what it says, then do what it asks. Bring one question with you: when you click the page after that, who is calling your code?
Related
- TypeScript: the same language, with its types checked before it runs.
- PHP: the server on the other end of a
fetch. - Java: exceptions, the way JavaScript reports that something failed.
- Dart: another language that leans on
asyncandawait, for drawing screens.
Tested with Firefox 153 ESR, November 2026.