Factorial in ECMAScript

Example for versions SpiderMonkey 1.7

This example uses recursive factorial definition and is meant to be executed from the web-browser. To run the example, copy its source text to a file factorial.js and create an HTML file placed in the same directory and containing the following text:

<head><script type="text/javascript" src="factorial.js"></script></head> <body></body>

When you open the HTML file, JavaScript code runs and writes its output to the page shown. document.clear() command clears everything that is written on the currrent web-page.

function factorial(n)
{   if (n == 0)
        return 1;
    else
        return n * factorial(n-1);
}
var i;
document.clear();
for (i = 0; i <= 16; i++)
    document.write(i + "! = " + factorial(i) + "<br />");