DEV Community

Muhammad    Uzair
Muhammad Uzair

Posted on

Factorial with Recursive Function in JS

Write a function to find a factorial of a number .
example: Factorial of 5! = 5*4*3*2*1

I have done this by implementing two methods:

By For Loop:

     function factorial(val){
         var numbers = val;
           for(let i = val-1; i > 0; i--) {
               numbers = numbers * i;
              }
         return numbers;
         }

By Recursion Method:

    function factorial(x) 
         { 
         if (x === 0)
         {
         return 1;
           }
       return x * factorial(x-1);
           }
     console.log(factorial(6));

Top comments (0)