JavaScript: Callback Function

Tay Bencardino
2 min readAug 7, 2022

A callback is a function or URL called after an event has occurred or when the program has reached the desired state.

  • accessible as a parameter by another function
  • is invoked after the first function if that first function completes

It is usually asynchronous (that is, it will not be executed immediately). And the application keeps running while the callback waits for its execution.

Imagine you want to eat dinner, but you must cook first. At the same time, your favourite playlist is playing, the water is boiling, and you are cutting some coriander. “Eat dinner” is not happening now. This would be the callback function because you must finish cooking first (the event) to eat the food!

The callback will help customize a code. For example, something will happen after some information is added to the database. Or something will happen after the user presses a button on the site.

Now imagine you have a web app that helps users to write a note, press the button “Add a note!” and the note will display on the web page.
The code below says: “Wait until the click to add a note”.

The user writes some notes and presses the button.
The value I received inside my input will be my new note.
The callback “addNewNote” is called. But this happened only because a button was pressed:

--

--