Factorial of number

OSCC · JavaScript, Math, Algorithm, Recursion · Dec 28, 2020

Calculates the factorial of a number.

  • Use recursion.
  • If n is less than or equal to 1, return 1.
  • Otherwise, return the product of n and the factorial of n - 1.
  • Throw a TypeError if n is a negative number.
const factorial = n =>
  n < 0
    ? (() => {
        throw new TypeError('Negative numbers are not allowed!');
      })()
    : n <= 1
    ? 1
    : n * factorial(n - 1);
factorial(6); // 720

Recommended snippets

  • Greatest common divisor

    JavaScript, Math

    Calculates the greatest common divisor between two or more numbers/arrays.

  • Least common multiple

    JavaScript, Math

    Calculates the least common multiple of two or more numbers.

  • Euclidean distance

    JavaScript, Math

    Calculates the distance between two points in any number of dimensions.