Java Reference
In-Depth Information
Notice the semicolon at the end of the closing brace in the function expression that
is the assignment statement terminator. You have given the function expression a name
called factorial . However, the name factorial is not available to be used as a function
name, except inside the function body itself. If you want to call the function, you must use
the variable in which you have stored the function reference. The following code shows
the use of the function name of the function expression inside the function body. This
code uses a recursive function call to compute the factorial:
var fact = function factorial (n) {
if (n <= 1) {
return 1;
}
// Uses the function name factorial to call itself
return n * factorial (n - 1);
};
var f1 = fact(3);
var f2 = fact(7);
printf("fact(3) = %d", f1);
printf("fact(10) = %d", f2);
fact(3) = 6
fact(10) = 5040
The function name in a function expression is optional. The code may be written as
follows:
// There is no function name in the function expression. It is an
// anonymous function.
var fact = function (n) {
if (n <= 1) {
return 1;
}
var f = 1;
for(var i = n; i > 1; f *= i--);
return f;
};
var f1 = fact(3);
var f2 = fact(7);
printf("fact(3) = %d", f1);
printf("fact(10) = %d", f2);
 
Search WWH ::




Custom Search