As explained in the MDN Web Docs, a callback function is
a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. I’d like to share a nice little trick you can do when passing in a named function.
But first, let’s look at an anonymous callback function, since these are (unfortunately) the most common.
Here’s a rather contrived example: imagine we wanted to listen for all
click events on the page, and log to the console the element which was clicked.
We might use an anonymous function, like so:
Instead, let’s move this into a named function,
Here’s where our nice little trick comes in. You might think we should call our new
logElement function like so…
…But this is actually superfluous. If you’re passing in a named function, you can just do the following, which is much cleaner:
You may be wondering how we can use the
logElement function without passing the
event argument to it. Remember that we’re simply passing in the name of a function we want to call at a later time—we’re not actually calling the function there and then, hence the lack of parentheses.
event argument gets passed in automatically because of the way the
EventTarget.addEventListener() method works. As explained in the MDN Web Docs:
The event listener can be specified as either a callback function or an object that implements
handleEvent()method serves as the callback function.
The callback function itself has the same parameters and return value as the
handleEvent()method; that is, the callback accepts a single parameter: an object based on
Eventdescribing the event which has occurred, and it returns nothing.
In other words, any callback function you pass to the
.addEventListener() method automatically gets the
Event interface passed in as an argument.
This works for any method which expects a callback function that accepts one or more arguments. Let’s look at another example: the
Let’s say I’m making a fruit salad. I have a shopping list of various fruits, which I’ve stored in an array called
The callback function you pass to the
.forEach() method accepts between one and three arguments:
currentValue (the current element being processed in the array),
index (the index of
currentValue in the array), and
array (the array
.forEach() was called upon).
I could loop through this array by passing in an anonymous function to log the name of each fruit and its index in the array…
…which would log the following to the console:
This works, but again, let’s avoid using an anonymous function. Instead, we’ll move this into its own named function (which we could then re-use on any array), called
We can now achieve exactly the same result as before while making our call to the
.forEach() method much more readable: