Computer >> Computer tutorials >  >> Programming >> Javascript

How does recursion function work in JavaScript?


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>