Java Reference
In-Depth Information
sum += arg;
}
// Compute and return the average
return sum / arguments.length;
}
The following snippet of code calls the avg() function:
// Load avg.js file, so the avg() function is available
load("avg.js");
printf("avg(1, 2, 3) = %.2f", avg(1, 2, 3));
printf("avg(12, 15, 300, 8) = %.2f", avg(12, 15, 300, 8));
avg(1, 2, 3) = 2.00
avg(12, 15, 300, 8) = 83.75
Function Expression
A function expression is a function that can be defined anywhere an expression can be
defined. The function expression looks very similar to a function declaration except that
the function name is optional. The following is an example of a function expression that
defines a function as part of an assignment expression:
var fact = function factorial(n) {
if (n <= 1) {
return 1;
}
var f = 1;
for(var i = n; i > 1; f *= i--);
return f;
};
/* Here, you can use the variable name fact to call the function,
not the function name factorial.
*/
var f1 = fact(3);
var f2 = fact(7);
printf("fact(3) = %d", f1);
printf("fact(10) = %d", f2);
fact(3) = 6
fact(10) = 5040
 
Search WWH ::




Custom Search