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:

button.addEventListener('click', () => console.log('Callback!'));

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:

function handleScroll() {
    // Code to be executed when the scroll event occurs
}

window.addEventListener('scroll', handleScroll);

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:

function handleKeyDown(event) {
    if (event.key === 'ArrowLeft') moveLeft();
    if (event.key === 'ArrowRight') moveRight();
}

document.addEventListener('keydown', handleKeyDown);

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:

function performOperation(callback) {
    console.log('Performing initial operation...');
    callback(); // Execute the provided callback function
    console.log('Operation completed!');
}

performOperation(() => console.log('Custom logic executed!'));

Links & Resources

  • Intersection ObserverDocumentation
  • Event Type ReferenceDocumentation
  • Keyboard Event KeysDocumentation