js-coding-challenges

Challenge 10: Find the Factorial of a Number

Write a function that takes a number as input and returns its factorial. The factorial of a number is the product of all positive integers from 1 to the number itself. For example, the factorial of 5 is 120 (1 _ 2 _ 3 _ 4 _ 5 = 120).

Write a function called factorial that takes a number as its parameter and returns its factorial. If the input number is 0, the function should return 1.

Answer

function factorial(num) {
  // Handle the case where the input is 0
  if (num === 0) {
    return 1;
  }

  let result = 1;

  // Multiply all numbers from 1 to num
  for (let i = 1; i <= num; i++) {
    result *= i;
  }

  return result;
}

Answer Explanation

The function takes a single argument num, which is the number to calculate the factorial for. Here’s what the function does:

Here’s an example usage of the function:

console.log(factorial(5)); // 120
console.log(factorial(0)); // 1
console.log(factorial(10)); // 3628800

In this example, the function correctly calculates the factorial of the input number and returns the correct result.