Recent Comments

Archives

Categories

Meta

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:

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.