Core JavaScript 1.5 Guide:Calling Functions
From MDC
[edit] Calling Functions
Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows.
square(5)
The preceding statement calls the function with an argument of five. The function executes its statements and returns the value twenty-five.
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The show_props function (defined in Objects and Properties) is an example of a function that takes an object as an argument.
A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:
function factorial(n) {
if ((n == 0) || (n == 1))
return 1;
else {
var result = (n * factorial(n-1) );
return result;
}
}
You could then compute the factorials of one through five as follows:
a=factorial(1); // returns 1 b=factorial(2); // returns 2 c=factorial(3); // returns 6 d=factorial(4); // returns 24 e=factorial(5); // returns 120