Java Reference
In-Depth Information
> pizza("Ham & Pineapple", eat);
<< "This is a Ham & Pineapple pizza"
<< "I've eaten the pizza!"
Okay, so in these examples, the cook() and eat() functions were quite similar, but they
should demonstrate that you could do something very different in the pizza function de-
pending on the callback function that is provided as an argument. This can make your func-
tions much more flexible.
Note that the callbacks cook and eat are passed as arguments without parentheses. This
is because the argument is only a reference to the function. The actual callback is invoked
in the body of the function, where parentheses are used.
A function can also take an anonymous function as a callback. For example, say we want to
deliver a pizza, but we have no deliver function. We can write an anonymous function
that does what we want:
pizza("Ham & Pineapple",function(){
console.log("The pizza has been delivered.");
});
This is only really useful for one-off tasks. It is often a much better idea to keep functions
separate and named so that they can be reused again. It's also a bad idea to use this method
for long function definitions as it can be confusing where the callback starts and ends.
Callbacks are used extensively in many JavaScript functions and we'll see much more of
them throughout the topic.
Sorting Arrays
In the last chapter we saw that arrays have a sort() method that sorted the items in the
array into alphabetical order. This is fine for strings, but it doesn't work so well for num-
bers:
> [1,3,12,5,23,18,7].sort();
<< [1, 12, 18, 23, 3, 5, 7]
Search WWH ::




Custom Search