Design & Download
Your JS Library
in Seconds!!!

Snippet: factorial()

Written by Christopher West (cwest) on August 24, 2016.
Calculate the factorial of an integer greater than or equal to 0.
function factorial(x) {
  if (isNaN(x = Math.floor(x, 10)) || x < 0) {
    throw new Error('Factorial can only be found for values greater than 0');
  }
  return x < 171 ? x > 1 ? factorial(x - 1) * x : x : (1 / 0);
}

factorial(...) API Documentation

Description

Calculate the factorial of an integer greater than or equal to 0. Factorial is calculated by multiplying a integer by each successively decreasing integer all the way down to 1. In other words 6 factorial (or 6!) is 6×5×4×3×2×1=720. Factorial of 0 is 0.

Parameters

  1. x {number}:
    The number for which to calculate factorial.

Returns

If the integer representation of x is 0, 0 is returned. If the integer representation of x is greater than 0 and less than 170 (limited by language), the product of the series of integers from 1 to x is returned. If the integer representation of x is greater than or equal to 171, Infinity is returned. In all other cases an error thrown.

Examples

console.log(YourJS.factorial(0));        // -> 0
console.log(YourJS.factorial(1));        // -> 1
console.log(YourJS.factorial(2));        // -> 2
console.log(YourJS.factorial(3));        // -> 6
console.log(YourJS.factorial(4));        // -> 24
console.log(YourJS.factorial(5));        // -> 120
console.log(YourJS.factorial(6));        // -> 720
console.log(YourJS.factorial(170));      // -> 7.257415615307994e+306
console.log(YourJS.factorial(171));      // -> Infinity
console.log(YourJS.factorial(99999999)); // -> Infinity
console.log(YourJS.factorial(Infinity)); // -> Infinity