Java Reference
In-Depth Information
function mean(array) {
return sum(array)/array.length;
}
And last of all, we can reuse the sum() , square() , and mean() functions together to
make a standardDeviation() function that calculates the standard deviation of an
array of numbers:
function standardDeviation(array) {
return sum(array,square)/array.length -
square(mean(array))
}
By separating each piece of functionality into individual functions, we're able to put to-
gether a more complex function. These functions can also be used to create other functions
that require the mean, sum, or square values.
Functions that Return Functions
As functions are first-class objects is that they can accept a function as an argument as well
as return another function.
This is the essence of functional programming: it allows generic higher-order functions to
be used to return more specific functions based on particular parameters. For example, we
can create a power() function that returns a function that calculates values to the power
of a given parameter:
function power(x) {
return function(power) {
return Math.pow(x,power);
}
}
Now we can create some more specific functions that use this generic function to build
them. For example, we could implement a twoExp() function that returns powers of 2 ,
like so:
Search WWH ::




Custom Search