How does recursion function work in JavaScript?

JavascriptWeb DevelopmentFront End Technology

When a function calls itself, it is called recursion and the same works for JavaScript too. Let’s see an example in which a function calls itself

Example

Live Demo

<html>
   <body>
      <script>
         function displayFact(value) {
            if (value < 0) {
               return -1;
            }
            // 0 factorial is equal to 1
            else if (value == 0) {
               return 1;
            } else {
               return (value * displayFact(value - 1));
            }
         }
         var res = displayFact(5);
         document.write("5 factorial = "+res);
      </script>
   </body>
</html>
raja
Published on 24-Jan-2018 06:45:41
Advertisements