DEV Community

loading...

Factorial with Recursive Function in JS

uzairsamad profile image Muhammad Uzair ・1 min read

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));

Discussion (0)

Forem Open with the Forem app