Functions and events

Code that runs when something happens, rather than straight away.

A function is a piece of code with a name, which runs when it is called.

function double(n) {
  return n * 2;
}

double(21); // 42

Most code in a browser does not run top to bottom and stop. It waits. A click, a keystroke, a page finishing loading — each is an event, and you hand the browser a function to run when one happens.

button.addEventListener("click", () => {
  count = count + 1;
});

The () => { … } is a function without a name, written where it is needed.

The order is not the order

The line after addEventListener runs immediately. The function inside runs later — maybe never, if nobody clicks. That difference is most of what makes browser code feel strange at first, and all of what makes it useful.

Try it

  1. Add a second button that takes one away.
  2. Make it refuse to go below zero.
  3. Change the text on the button to show the count itself.
Loading...