Skip to content

Instantly share code, notes, and snippets.

@muzfuz
Last active October 20, 2015 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muzfuz/cb9651393dc241ab1e38 to your computer and use it in GitHub Desktop.
Save muzfuz/cb9651393dc241ab1e38 to your computer and use it in GitHub Desktop.
The introduction to callbacks that I wish I'd had.

The introduction to JavaScript callbacks that I wish I'd had when I was starting out.

When I first started learning to code, I found the concept of callbacks extremely confusing. Which is funny, because I was using them all the time without realising it - If you currently use jQuery, then you are already using callbacks. (More on this later).

So here's my attempt to try and explain callbacks in as simple a way as I can. I'll probably gloss over some details here, but keep in mind this is a beginner's guide. If you see any glaring errors, feel free to ask me to change it.

So here goes:

##Basic definition: ####A callback is a function that is passed as an argument to another function.

That's basically it.

##How does this look in practice? Consider the following:

//First function, expects a callback
function firstFunction(callback) {
  callback('hello')
}

//Second function, expects a string
function secondFunction(string) {
  console.log(string);
}

//Now call them
firstFunction(secondFunction);

//Writes 'hello' to the console.

Congratulations. You just used a callback function. If you don't get what's going on above, try to write it out yourself and run the code in something like jsBin.

Do you see what's going on here? firstFunction expects to receive a function as an argument. This is important, because if we were to pass in something like an integer or a string instead of a function, then we would get an error.

secondFunction expects a string (or really, anything since it's just logging to the console, but let's pretend that it requires a string for the sake of argument). This string is supplied by firstFunction.

This is really the simplest, and most basic explanation of callbacks. Make sure you understand this, because everything that follows will build on the above example.

##Take a look at the above example again.

Did you notice how firstFunction passes only one argument to its callback?

And also, that secondFunction only expects to receive one argument?

This is important, because the number of arguments and the type of data they pass around is something that you need to be aware of when you're using callbacks.

In our example, firstFunction will pass only one argument to whatever callback it receives. So secondFunction needs to be written to receive only one argument. Doing something like this will cause problems:

secondFunction(string, number) {
  number += 1;
  console.log(string, number)
}

Some functions will pass multiple arguments to their callbacks, with multiple datatypes. If this isn't crystal clear to you right now, don't worry. With trial and error, and reading the documentation, you'll be able to figure it out.

##Ok so far so good. Let's take a look at some jQuery code.

$('#link').click(function(){
  //Do stuff
});

What's going on here? Let's break this down into it's component parts.

#####1. The $ jQuery function.
This is the first function you are calling. $ is just the name of that function. Somewhere in the jQuery library is code that looks something like this:

function $(){ 
  //jQuery source code 
}

It's really that simple. $('#link') is the $() function with '#link' as its argument.

#####2. #link This is the DOM element that you have selected.

#####3. .click() This is an event handler - it's a special type of function that gets executed when certain things happen in the DOM. In this case, when a user clicks on the selected element, the .click() function is called. The click function expects a single function as its argument, which it executes. The source code for the .click() function might look something like this:

Disclaimer: this is totally not what it looks like in reality - it's a massive simplification to serve a point!

function click(callback){
  callback() //execute callback
}

#####4. function(){//Do stuff} Ok so this is it. This is our callback function.

But hang on, this looks different from the first example of callbacks! Well, not really.

Remember, in JavaScript you can use anonymous functions (that is, functions without a name) that you instantiate immediately. To illustrate this point, consider the following example:

function doStuff() {
  //Do stuff
}

$('#link').click(doStuff);

This is basically the same thing as writing:

$('#link').click(function(){
  //Do stuff
});

It's just no longer using an anonymous function, which means that you can re-use doStuff wherever you like.

So when should you use anonymous functions? A good rule of thumb is, if you're not planning on reusing the bit of code that you're writing, then you can go ahead and make it anonymous.

##The most important thing you need to know about callbacks

####Using callbacks is like playing a game of hot-potato. You have a piece of data that you are passing from function to function to function. There's a good chance that you will not return this data.

If you're coming to JavaScript from Ruby then you're probably very comfortable with thinking about functions as things that return data. You put something into it, and then you get something back.

function returnNumber(data) {
  return data;
}

returnNumber(12);
//12

The function above does exactly what it says. It returns a number (12, in this case). But consider again our first example:

//First function, expects a callback
function firstFunction(callback) {
  callback('hello')
}

//Second function, expects a string
function secondFunction(string) {
  console.log(string);
}

//Now call them
firstFunction(secondFunction);

//Writes 'hello' to the console.

None of these functions return anything, but you're still getting something to show the user. This is the fundamental thing about callbacks - their name somehow implies that you are 'calling back' to the past, but what you are actually doing is throwing information forward to be used at some point in the future.

###To summarise, here are some basic rules about callbacks:

  1. A function that accepts a callback will expect to receive that callback in a specific format. This is the initial function will (probably) pass data to that callback.
  2. If you are using a library or framework (like jQuery or Express.js), it's up to you to understand how the functions you are using expect the callbacks to be formatted. The best way to learn this is through experience, and to read the documentation.
  3. Remember that a callback can be an anonymous function.
  4. Don't expect your callbacks to return data.
  5. Callbacks can get confusing quickly. Just keep reminding yourself that even though it's called a callback, what it's actually doing is passing information forward.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment