Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Follow publication

More on JavaScript Functions

Photo by Eric Prouzet on Unsplash

Difficulty: Beginner

In the previous article, I talked about the concept of functions and how to create them. We defined its basic structure and use. I believe functions are one of the more (most) important concepts in JavaScript. Building upon the basics of functions, let’s look at one of the most fundamental concepts in JavaScript: callbacks, or callback functions.

What the bleep is a callback?

I have to admit, I struggled with this concept for a long time, not seeing the connection between what I was putting into practice and what I had learned. I’d always thought the name ‘callback’ was misleading, and gave you the impression it was somehow a magical concept; after all, who’s calling who back? Well, it’s not magic, it’s just a natural part of what a function is.

I teach a full-stack JavaScript bootcamp, and one of the very first things I teach in JavaScript are functions. We talk about how functions are first class citizens, and the fact that they can be passed around like variables, assigned to variables (not just the result, but the actual uninvoked function), and called/invoked later. Students nod their head in understanding, because it’s really not a very difficult concept to grasp. Yet, when we invariably try to put the concept into practice by using callbacks, it’s like I’m speaking a foreign language. Why?

Think of a callback function as a TV remote you can pass around from person to person. Any one of these people can press (invoke) a button to change the channel. A callback is simply a function definition you pass around. Take note, I say, because understanding this concept will be critical in understanding everything from event handlers in Vanilla JS, to lifting state in React.

Using the above remote control analogy… say your cousin Bob is sitting on the couch (he’s the event handler). Bob’s sole purpose in life is to listen to requests that people in the TV room have for turning up the volume, changing the channel, etc. Bob’s a great listener, but if Bob doesn’t have a remote control, Bob can’t do anything. So you, as the great host you are, give Bob the remote control (the function). You pass it to Bob, no buttons pressed yet (uninvoked). The moment you give the uninvoked function to Bob, by definition it becomes a callback function. Bob now has the ability to respond to requests from people in the room by using the remote to call/invoke the function (press button). Maybe “callback” should be renamed “the uninvoked function definition you pass as a variable to be invoked later” function…. well, maybe not.

As you can see, I am extremely explicit and painfully obvious, assuming nothing. I personally wish more articles I’d read in the past had been this way. It would have made life so much easier learning. Even in a live class, instructors make certain assumptions about baseline knowledge, and if students don’t ask/clarify, the moment is lost. I will try not to do that here.

Simple Callback Example:

function bark() {
return 'woof';
}
function doDogStuff(event, response) { if (event === 'intruder'){ console.log(response()); //output 'woof' to console }else { console.log('doing nothing'); // output 'doing nothing' }}doDogStuff('intruder', bark);
doDogStuff('homeowner', bark);

In the above simple example, bark is a function that returns ‘woof’, doDogStuff is a function that takes in an event parameter (in our case a simple string) and a response parameter ( in our case, it is expecting a variable that represents a function).

When doDogStuff is invoked, an event string (‘intruder’, or ‘homeowner’) and the variable ‘bark’ are passed in as arguments. the variable ‘bark’ represents an uninvoked function.

This is the key point: bark is the TV remote with no buttons pressed, and it’s being passed to Bob (doDogStuff), who’s in charge of pressing it when the moment is right.

We won’t know when the bark function will be invoked because we don’t control it (Bob does). ‘bark’ only gets invoked if the event is ‘intruder’. Note also that inside the doDogStuff function, ‘response’ is the variable that holds the bark function now. So in order to invoke the bark function inside of doDogStuff, you invoke response(). Yes, you can invoke bark() directly, but that would not be very good functional programming practice.

The Common Event Listener and Callback response:

Let’s try a more common example, one that is seen literally everywhere. The DOM Event Listener pattern is the classic example used when explaining callbacks. This did not make sense to me in the beginning without a simpler example, hence the reason for the TV remote analogy and the above simple case. To set things up, we’ll need to create a simple html button and an index.js file referenced in the html:

index.html

<html>  <body>    <button id="myButton"></button>  </body>
<script src="./index.js"></script>
</html>

index.js

let myButton = document.getElementById('myButton')myButton.addEventListener('click', response);function response() {    console.log('I was clicked')}
  • addEventListener function is analogous to our doDogStuff function above
  • ‘response’ is analogous to our bark function above
  • ‘response’ is passed in to the addEventListener as a variable
  • when ‘click’ happens, we trust that the response callback function is invoked… just like in our simple example
  • No, you don’t actually see the invocation, but it does happen (it’s part of the DOM methods). We see the result by the fact that console.log(‘I was clicked’) gets executed

There you have it… callback functions in its most verbose and unassuming form. The key here is, you define a function and give it a name. You can then pass that name (variable) anywhere you like. Then… some other entity, be it another function or code, can invoke it at an appropriate moment.

I hope this helped in your understanding of what a callback function is. Please drop me a note or if you have any comments. Now… get back to coding!

Previous: What Are JavaScript Functions?

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Calvin Cheng
Calvin Cheng

Written by Calvin Cheng

A yawn is a silent scream for coffee — Unknown Author

No responses yet

Write a response