javascript function
Functions are Data
This is an important concept that we'll need later on—functions in JavaScript
are actually data. This means that the following two ways to define a function
are exactly the same:
function f(){return 1;}
var f = function(){return 1;}
Callback Functions
Because a function is just like any other data assigned to a variable, it can be defined,
deleted, copied, and why not also passed as an argument to other functions?
Here's an example of a function that accepts two functions as parameters, executes
them, and returns the sum of what each of them returns.
function invoke_and_add(a, b){
return a() + b();
}
Now let's define two simple additional functions that only return hardcoded values:
function one() {
return 1;
}
function two() {
return 2;
}
Now we can pass those functions to the original function add() and get the result:
>>> invoke_and_add(one, two);
3
Another example of passing a function as a parameter is to use anonymous
functions. Instead of defining one() and two(), you can simply do:
invoke_and_add(function(){return 1;}, function(){return 2;})
When you pass a function A to another function B and B executes A, it's often said
that A is a callback function. If A doesn't have a name, then you can say that it's an
anonymous callback function.
When are the callback functions useful? Let's see some examples that demonstrate
the benefits of the callback functions, namely:
- They let you pass functions without the need to name them (which means
there are less global variables)
- You can delegate the responsibility of calling a function to another function
(which means there is less code to write)
- They can help with performance