Saturday 1 September 2018

JavaScript: Recursion

Recursion is a technique, where a function can call itself. For example, following function calculates the factorial of a number using recursion.

function factorial(n){
         if(n < 2)
                  return 1;
         return n * factorial(n-1);
}

There are three ways that a function can refer to itself.
a.   By using function name
b.   By using arguments.callee
c.   By using an in-scope variable that refers to the function

By using function name
function factorial_1(n){
         if(n < 2)
                  return 1;
         return n * factorial_1(n-1);
}

By using arguments.callee
function factorial_2(n){
         if(n < 2)
                  return 1;
         return n * arguments.callee(n-1);
}

By using an in-scope variable that refers to the function
var factorial_3 = function factorial(n){
         if(n < 2)
                  return 1;
         return n * factorial_3(n-1);
}

factorial.html
<!DOCTYPE html>

<html>

<head>
    <title>Factorial</title>
</head>

<body>
    <script type="text/javascript">
        // By using function name 
        function factorial_1(n) {
            if (n < 2)
                return 1;
            return n * factorial_1(n - 1);
        }

        // By using argument.callee
        function factorial_2(n) {
            if (n < 2)
                return 1;
            return n * arguments.callee(n - 1);
        }

        // By using in-scope variable
        var factorial_3 = function factorial(n) {
            if (n < 2)
                return 1;
            return n * factorial_3(n - 1);
        }

        document.write("Factorial of 5 is " + factorial_1(5) + "<br />");
        document.write("Factorial of 10 is " + factorial_2(10) + "<br />");
        document.write("Factorial of 20 is " + factorial_3(20) + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

Factorial of 5 is 120
Factorial of 10 is 3628800
Factorial of 20 is 2432902008176640000



Previous                                                 Next                                                 Home

No comments:

Post a Comment