Java Reference
In-Depth Information
Remember at the start of this chapter when we said that functions in JavaScript are first-class
objects, and this means that they behave in just the same way as every other value? Well,
they can also be given as a parameter to another function. A function that is passed as an
argument to another is known as a callback .
Here's a basic example of a function called pizza , which accepts an argument for the type
of topping that goes on the pizza, as well as a callback function saying what to do with the
function pizza(topping, callback) {
console.log("This is a " + topping + " pizza");
Now we can create some utility functions for what we do with pizzas, such as cook them
and eat them:
function cook() {
console.log("The pizza is cooking");
function eat() {
console.log("I've eaten the pizza!");
We're just logging some simple messages to the console in these examples, but these func-
tions could be used to do anything in a practical sense.
Let's have a go at using these utility functions as callbacks in our pizza function:
> pizza("Ham & Pineapple", cook);
<< "This is a Ham & Pineapple pizza"
<< "The pizza is cooking"
Search WWH ::

Custom Search