Callbacks in real code
Callbacks are everywhere. In most code bases, they are used to react to events - clicks, scrolls, key presses - or they are passed to higher order functions that call them for us.
Event handling
If an event happens, the callback function is invoked. To do this, an event listener must be set up for that specific event:
Usually the callback is a well-named function of its own. Notice that we pass the function reference - no ( ) - because we don't want it to run now. We want the browser to run it later, when the event happens:
Many callbacks receive an argument from whoever calls them. A key press handler receives an event object, and inside it, a .key property tells us which key was pressed:
We didn't choose that argument - the docs for keydown tell us what we'll receive. That's the rule with every callback: you write the function, but someone else decides when to call it and what to pass in.
Our own functions that receive callbacks
We can also write functions that accept a callback, do some work, and then call it: