In the previous article in this series, we talked about declaring functions. That ended with an explanation of arrow functions, which are great for use as callback functions. Now, we’ll go into exactly what callback functions are and how to use them.
Calling Plays in Specific Scenarios
I’ve been using the analogy that a function is like a play in football because it’s a sequence of steps that are carried out anytime someone calls it by name, very much like a play. Sometimes, it’s nice to be able to set triggers on plays.
I’ve never been a coach of any sport, but I can imagine giving a trusted player some leeway to change the play if they see a specific scenario. “This play is really good against this specific type of defensive setup. If you see the other team setting up that way, go ahead and change to this play.” Sometimes the players can see things maybe the coach can’t. It would be good for them to know which scenarios are good for which plays so they can change on the fly.
A Better Analogy
The sports play analogy is a bit of a stretch to describe callback functions, but I do love me some analogies. Here’s another one that works better.
You get sick, so you go to the doctor. The doctor diagnoses you and can tell you have an infection. They’re going to treat it with antibiotics.
Does the doctor give you a dose of the medication and ask you to come back at certain times each day for the other doses, or does the doctor give you a prescription along with instructions on when to take it? Unless you have much better insurance than me, it’s always going to be the latter.
What if the doctor could give you the medicine but had no way to tell you when to take it? The only way you’ll take the medicine is if the doctor calls you at the correct time to get you to take it. The doctor knows you need to take the medicine after breakfast and before bed but has no idea when those times will be for you, nevermind they might change on a daily basis. You’re the best person to execute this plan, because you know the most about you and your schedule.
A Real Use Case for Callback Functions
A callback function is a set of instructions you pass into another function to tell it what to do at some later time. The callback function oftentimes runs when the function is done doing whatever it will do or when some event occurs. You as the programmer don’t necessarily know when these things will happen, so the function you’re passing you’re callback into will look out for that for you.
Let’s make this more concrete. Imagine you’re writing an application with views that can be customized with your user’s name. You’ve added a text field where the user can enter their name, and a button to click once they’ve entered it. When they click, it should add their name to the page.
You have no way of knowing when the user will enter their name, so you can’t just put the code to get their name and insert it on the page at the exact right place in your code. They may sit on the page for 10 minutes before entering their name. They might never enter it.
Instead, you’re going to use an event listener. This is a function you call that will watch for the user to click on the button. When they do, it will call whatever function you’ve passed into it. That function is the callback function. Here’s what it might look like:
The key here starts on line 4.
document.querySelector('#personalize-button').addEventListener('click', (event) => {
nameBlank.textContent = nameField.value;
});
With document.querySelector('#personalize-button')
, I’m selecting the button element labeled “Personalize.” That’s where the click happens, so that’s where I’ll put the event listener.
I chain off that to add the event listener. The addEventListener
method takes the event to listen for as its first argument. I’ve passed `click`
since that’s the event I care about.
The next argument to addEventListener
is the callback function. If I’ve declared the function, I can pass in the name of the declared function. Since this is the only thing I’ll use this function for, I don’t really need to declare it. I can pass in the function directly as an anonymous function. (That just means the function doesn’t have a name.) This is the technique I’ve used here.
The result is that, when the user clicks on the “Personalize” button, the event listener calls the callback function we passed into it. That function has code to replace the blank in the text with the name the user entered.
To go back to the medical analogy from earlier, the callback function is like our prescription. The event listener knows when it should take the medicine (after the user clicks the button), but it doesn’t have the medicine it needs to take (the callback function).
I’ve done the piece I’m uniquely suited to do as the developer: I’ve told the event listener what to do when the event happens. The event listener does the piece it’s uniquely suited to do: it’s determined the correct timing for calling the callback function I gave it.
Other Uses for Callback Functions
Callback functions are used for more than just responding to events. They’re used in many of the array methods like reduce and map. They’re used to respond to asynchronous functions too. These functions continue running in the background as the rest of your code runs as well. One method for responding to the completion of these operations is to pass in a callback function.
Now that you know the common uses for functions and how to declare them, let’s refactor some existing code to be better by implementing functions. If you want to join in the fun, follow me here on Dev.to or head over to Rad Devon. There you can sign up to get notified when the refactoring article is live, but you'll also have a chance to get a free 🎁 30-minute mentoring session 🎓 with me 👋. We'll map out the next steps you need to take to continue your transition from 💩 job to web developer!
Articles in This Series
- Your App’s Playbook: Why Use Functions in Javascript
- Declaring Javascript Functions
- Understanding Javascript Callback Functions
- Marie Kondo Your Javascript Code with Functions
Top comments (0)