Java Reference

In-Depth Information

if (typeof callback === "function") {

total += callback(values[i]);

} else {

total += values[i];

}

Let's have a go at using it:

> mean([2,5,7,11,4]); // this should just calculate the

mean

<< 5.8

Now let's use an anonymous function to double all the numbers before calculating the

mean:

> mean([2,5,7,11,4],function(x){ return 2*x; });

<< 11.6

This is the equivalent of calculating the mean of 2 * 2, 2 * 5, 2 * 7, 2 * 11, and 2 * 4.

Last of all, let's use the
square
function that we wrote earlier in this chapter as a callback

to square all the numbers before calculating the mean:

> mean([2,5,7,11,4],square);

<< 43

This is the equivalent of calculating the mean of 2^2, 5^2, 7^2, 11^2, and 4x^2.

I trust these examples show how using callbacks can make functions much more powerful

and flexible.