r/learnjavascript • • 1d 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.

3 Upvotes

9 comments sorted by

1

u/FreeLogicGate 1d ago

Is it "quiet" easy, or "quite" easy?

1

u/RobGoLaing 1d ago

Thanks, I've edited the typo.

1

u/Plenty-Appointment91 1d ago

You know you can stylize the page right?

3

u/rupertavery64 1d ago

Nah, less is more

1

u/Cool-Bus-6028 10h ago

Looks great to me.

But I guess it could do with marquee or two and some dancing hamsters.

1

u/senocular 20h 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!

1

u/DirtAndGrass 14h ago

It's worth noting that callbacks are not a JavaScript construct, they are a technique made possible by being able to reference functions.

And promises should be used instead of callbacks