How do I calculate the factorial of a number in JavaScript?
Alex K
alex k profile pic

To calculate the factorial of a number in JavaScript, you can use a recursive or iterative approach. Here's a step-by-step guide on how to achieve this: 1. Define the number for which you want to calculate the factorial:

1
2
3

   const number = 5;
   

Replace5 with the actual number for which you want to calculate the factorial. 2. Recursive Approach: The recursive approach involves defining a function that calls itself with a decreasing number until it reaches the base case.

1
2
3
4
5
6
7
8
9
10
11

   function factorialRecursive(n) {
     if (n === 0) {
       return 1; // Base case: factorial of 0 is 1
     }
     return n * factorialRecursive(n - 1);
   }

   const factorial = factorialRecursive(number);
   console.log(factorial);
   

In this example, thefactorialRecursive function takes the numbern as an argument. Ifn is 0, it returns 1 as the base case. Otherwise, it recursively calls itself withn - 1 and multiplies the currentn with the result. 3. Iterative Approach: The iterative approach involves using a loop to calculate the factorial by continuously multiplying the numbers from 1 ton.

1
2
3
4
5
6
7
8
9
10
11
12

   function factorialIterative(n) {
     let result = 1;
     for (let i = 1; i <= n; i++) {
       result *= i;
     }
     return result;
   }

   const factorial = factorialIterative(number);
   console.log(factorial);
   

In this example, thefactorialIterative function takes the numbern as an argument. It initializes theresult variable to 1 and uses a for loop to multiplyresult with each number from 1 ton. Both the recursive and iterative approaches will yield the same factorial result. Choose the approach that best fits your use case and the size of the number you're calculating the factorial for. By following these steps, you can calculate the factorial of a number in JavaScript. Adjust the code as needed to fit your specific requirements and handle different input values.