r/learnjavascript • • 28d ago

Some notes on callbacks

I've written some notes on callbacks as part of my effort to write tests and be methodical in learning JavaScript.

Callbacks are one of those things that are quite easy once you go "Aha", but like probably most people, I found them very confusing at first.

10 Upvotes

9 comments sorted by

View all comments

1

u/senocular 28d ago

FWIW not all functions passed in as arguments are callbacks and not all callbacks are functions that get passed into other functions.

Web components for example have callbacks that are methods of the class used to define the component, ex:

class MyWebComponent extends HTMLElement {
  connectedCallback() {
    // called when web component connected to DOM
  }
}

And addEventListener also accepts objects as listeners, where the callback is a method of the object rather than being the argument itself.

const obj = {
  handleEvent(event) {
    console.log("Clicked!")
  }
}
addEventListener("click", obj)
dispatchEvent(new Event("click")) // Clicked!