Java Reference
In-Depth Information
fact(3) = 6
fact(10) = 5040
You can also define a function expression and call it in the same expression. The
following code shows how to define and call a function expression in two different ways:
// Load the avg.js file, so the avg() function will be available
load("avg.js");
// Encloses the entire expression in (). Defines a function expression and calls
// it at the same time.
(function printAvg(n1, n2, n3){
// Call the avg() function
var average = avg(n1, n2, n3);
printf("Avarage of %.2f, %.2f and %.2f is %.2f.", n1, n2, n3,
average);
}(10, 20, 40));
// Uses the void operator to create an expression. Defines a function
// expression and calls it at the same time.
void function printAvg(n1, n2, n3) {
var average = avg(n1, n2, n3);
printf("Avarage of %.2f, %.2f and %.2f is %.2f.", n1, n2, n3, average);
}(10, 20, 40);
Avarage of 10.00, 20.00 and 40.00 is 23.33.
Avarage of 10.00, 20.00 and 40.00 is 23.33.
First, the avg.js file is loaded that defines the avg() function. A function expression
needs to be enclosed in parentheses or preceded by the void operator to help the parser
not to confuse it as a function declaration. The function arguments list follows the
function expression closing brace. In the second case, you have used the void operator
instead of parentheses. The parser will be able to parse the function argument properly
as it expects an expression after the void operator, not a function declaration. You could
have dropped the function name in the code in both function expressions.
 
Search WWH ::




Custom Search