ChApter 1 ■ JAvASCrIpt You Need to KNow
Callbacks
Callbacks can be a bit confusing, both for new programmers and for seasoned professionals alike (at least for those
new to the functional programming style upon which callbacks are based). The key to enlightenment, I think, is first to
understand that functions are objects that can be passed around just like any other value in JavaScript.
Let’s step through this slowly. Listing 1-30 provides an example that shows how you can create a variable and
then store a function in that variable.
Listing 1-30. Storing a Function Reference in a Variable: Part 1
<!DOCTYPE html>
Listing 1-30 is quite short, but a particularly important concept is illustrated within it. We start off by declaring a
variable called myFunctionReference, in which we store a function or, rather, a reference to a function.
You might think that the function looks a little odd; it has no name. That’s OK because it is stored in the variable
myFunctionReference, so when we want to use this function, we can use the parentheses to call it.
Look closely at the last three lines. In two cases, I use the parentheses, but in one case, I do not. In the case in
which I do not, the function reference is not called (or invoked). It is the parentheses, also known as the call operator,
that cause the function to run. Here are the results:
callbacks part 1
callbacks part 1
This idea that functions are themselves values that can be assigned to variables is important. Listing 1-31 is done
in a way that may (or may not) seem more intuitive, if you have not used anonymous functions (functions without a
name) before.