Fun with Callbacks

This is a quick summary of callbacks as they seem to be a highly important topic in JS. A great resource to read if you haven’t already is here.

So what are callbacks?

First a little background knowledge on functions – functions in JS are considered first-class objects. While the intricacies of this point still escape me, what I understand of it is that it means that like any other object (String, Number, Array, etc), (“stored in variables, passed as arguments to functions, created within functions, and returned from functions”).

Let’s focus on a few of these points.

As I mentioned earlier, here some of the ways we can see functions being built:

//Function declaration
function foo() { return 5; }

//Anonymous function expression
var foo = function() { return 5; }

//Named function expression
var foo = function foo() { return 5; }

A callback function is a function that is passed into a function as an argument and then returned or executed at some point later within that outer function.

Callback functions can essentially be thought of as patterns or an established solution to a common problem.

When we pass callbacks into a function, we are only passing in the function definition, it is not being executed. Thus, we can think of some interesting way to use callbacks. They can be stored in variables and then passed in as an argument or they can be set up as anonymous function expressions in the arguments space.

A quick thing to note is that because a callback function is essentially defined inside the outer function, it is considered a type of closure.

Basic Principles

  • You can use named or anonymous functions.
  • It is a good check to make sure that a callback is a function before using it.
  • You have to be careful when you use methods that use the this object when using callbacks.
  • When you execute a callback, it will either point to the window object if it is a global function calling it or the object of the containing method.
  • We can use the apply or call methods to remedy the previous issue

Why Callbacks?

  • They help us not repeat code (DRY)
  • More readable code
  • Less room for errors
  • More abstraction (generic functions that are more powerful)
  • Asynchronous execution
Fun with Callbacks

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s