JavaScript recursive function

In JavaScript, you can create a recursive function that can call itself until a base case is met. Without the base case, the function will call itself infinitely. In the example code below, fact recursive function is called to calculate the factorial value of a number input by the user. The base case of the function is "n<=1" and the general case is "n*fact(n-1)".
<html>
<head>
<title>Recursive Function</title>
<script type="text/javascript">
function fact(n){
if (n<=1) return 1;
else return(n*fact(n-1));
}
var num=prompt("Enter n:");
alert(fact(num));

</script>

</head>
<body>

</body>
</html>

Posted by: Dara | post date: 03-23-2013 | Subject: JavaScript




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.